Py学习  »  Python

如何使用selenium和python在dd属性中提取没有名称的文本?

Bob Stone • 7 年前 • 2062 次点击  

我有一个带有dd值的网页。代码如下:

<dd itemprop="youSave" 
class="saleprice pricingSummary-priceList-value" 
style="width: 50%; height: 20px; text-align: left; padding-left: 8px; line-height: 16px;">
$467.99</dd>

如何使用selenium和python拉取价格(467.99美元),同时去掉美元符号?

这是我当前的代码,它提取保存的价格,但无法获取属性:

try:
    while True:
        price_saved = driver.find_elements_by_xpath("//dl[@class='dl']//dd")
        print("ok")
        saved_print = price_saved.get_attribute("*Don't know what to put here*")
        print("k")
        print(saved_print)
        i = i + 1
except:
    print("failed")
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/46071
文章 [ 1 ]  |  最新文章 7 年前
QHarr
Reply   •   1 楼
QHarr    7 年前

以下是一些取决于整个html的可能性

#class selector

driver.find_element_by_css_selector('.pricingSummary-priceList-value').text.replace('$','')

#attribute selector
driver.find_element_by_css_selector('[itemprop=youSave]').text.replace('$','')

#combined
driver.find_element_by_css_selector('[itemprop=youSave].pricingSummary-priceList-value').text.replace('$','')

#combined with type selector
driver.find_element_by_css_selector('dd[itemprop=youSave].pricingSummary-priceList-value').text.replace('$','')

如果需要多个匹配项,则使用列表理解示例( find_elements 返回列表):

[i.text.replace('$','') for i in driver.find_elements_by_css_selector('[itemprop=youSave]')]

类比类型快,类型比属性快。在某种程度上,短组合比长组合更快,这取决于之前给出的规则和顺序,但这超出了本文的范围。

我使用了一个多值类的单个类。你可以在其他类中添加

driver.find_element_by_css_selector('.saleprice.pricingSummary-priceList-value').text.replace('$','')