Ant*_*ych 2 selenium python-3.x selenium-webdriver
我试图从这个亚马逊页面获取元素,这是产品的平均评论率。它位于这里:
在检查控制台中,这部分显示如下:
<span data-hook="rating-out-of-text" class="a-size-medium a-color-base">4.4 out of 5</span>
Run Code Online (Sandbox Code Playgroud)
我的代码是:
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--incognito')
driver = webdriver.Chrome(chromepath, chrome_options=chrome_options)
driver.maximize_window()
driver.get('https://www.amazon.com/dp/B07B2STSLV')
driver.find_element_by_class_name("a-size-medium a-color-base")
Run Code Online (Sandbox Code Playgroud)
期望的输出是:
4.4 out of 5
Run Code Online (Sandbox Code Playgroud)
但它返回错误:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".a-size-medium a-color-base"}
(Session info: headless chrome=85.0.4183.121)
Run Code Online (Sandbox Code Playgroud)
所以显然这种方法行不通。我还尝试了几种使用 css 选择器的方法:
driver.find_elements_by_css_selector("span.a-size-base a-nowrap")
Run Code Online (Sandbox Code Playgroud)
并通过xpath获取元素:
driver.find_element_by_xpath('//*[@id="reviewsMedley"]')
Run Code Online (Sandbox Code Playgroud)
但两者都不起作用
关于如何获得它有什么想法吗?
find_element_by_class_name
您在ie中使用了 2 个类a-size-medium
,并且a-color-base
class_name 选择器不支持复合类。这就是为什么它不起作用
这driver.find_elements_by_css_selector("span.a-size-base a-nowrap")
也不起作用,因为两个类a-size-base
都a-nowrap
属于相同的标签,即<span>
简而言之,您必须使用.
代表类的点来组合同一标签中的所有类。
css 路径看起来像 -
driver.find_element_by_css_selector("span.a-size-base.a-nowrap").text
Run Code Online (Sandbox Code Playgroud)
您可以在 xpath 中使用复合类,如下所示
driver.find_element_by_xpath("//span[@class='a-size-base a-nowrap']").text
Run Code Online (Sandbox Code Playgroud)
您的情况中出现了一次 require 元素,因此请使用find_element
而不是find_elements
。
归档时间: |
|
查看次数: |
1828 次 |
最近记录: |