gpt4 book ai didi

python - 有没有办法从 CSS 选择器中获取特定文本?

转载 作者:行者123 更新时间:2023-12-01 07:36:18 24 4
gpt4 key购买 nike

我希望在检查元素时获取 css 选择器的所有 #text 部分。我似乎正在抓取选择器下的所有数字而不是文本部分。

我抓取的链接是 https://www.virginmobile.ca/en/phones/phone-details.html#!/gs9/Grey/64/TR20

我想获取“选择您的手机价格”下的价格,但字符串末尾没有“$”和“99”美分

目前我只熟悉抓取整个字符串。

    driver.get(link)
time.sleep(3)
print('--------------------------- begining ------------------')

planTypeUpfrontCostListRaw = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '#phonePricesList .ultra')))

for element in planTypeUpfrontCostListRaw:
upfrontCost = element.text
print(upfrontCost)

print('--------------------------- END ------------------------')

最佳答案

解决方案1
不要使用 text,而是使用 innerHTML。这将返回该元素的 html 代码,包括文本!

例如,它将返回您:

"<sup>$</sup>199<sup>99</sup>"

然后您可以使用正则表达式库re仅获取中间的值。

print(re.search('\d+', upfrontCost).group(0))

输出:199

这是执行此操作的代码:

from selenium.webdriver import Chrome
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
import re

link = "https://www.virginmobile.ca/en/phones/phone-details.html#!/gs9/Grey/64/TR20"
driver = Chrome()
wait = WebDriverWait(driver, 15)
driver.get(link)
print('--------------------------- begining ------------------')

planTypeUpfrontCostListRaw = wait.until \
(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '.price.ultra.ng-binding.ng-scope')))

for element in planTypeUpfrontCostListRaw:
upfrontCost = element.get_attribute('innerHTML')
upfrontCost = re.search('\d+', upfrontCost).group(0)
print(upfrontCost)
print('--------------------------- END ------------------------')

输出:

---------------------------  begining ------------------
0
0
199
349
739
1019
--------------------------- END ------------------------

解决方案2
您仍然可以使用 text 并使用 strip 删除不需要的数据 $ 并删除最后两位数字。

driver = Chrome()
wait = WebDriverWait(driver, 15)
driver.get(link)
print('--------------------------- begining ------------------')

planTypeUpfrontCostListRaw = wait.until \
(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '.price.ultra.ng-binding.ng-scope')))

for element in planTypeUpfrontCostListRaw:
upfrontCost = element.text.strip('$')
if upfrontCost != '0':
upfrontCost = upfrontCost[:-2]
print(upfrontCost)
print('--------------------------- END ------------------------')

关于python - 有没有办法从 CSS 选择器中获取特定文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56978827/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com