首页 > 解决方案 > Selenium 无法按类名找到元素

问题描述

我正在尝试从这个亚马逊页面获取元素,这是产品的平均评论率。它位于这里:

在此处输入图像描述

在检查控制台中,这部分显示如下:

<span data-hook="rating-out-of-text" class="a-size-medium a-color-base">4.4 out of 5</span>

我的代码是:

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")

所需的输出是:

4.4 out of 5

但它返回 en 错误:

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)

所以显然这种方式是行不通的。我还尝试了几种使用 css 选择器的方法:

 driver.find_elements_by_css_selector("span.a-size-base a-nowrap")

并通过 xpath 获取元素:

driver.find_element_by_xpath('//*[@id="reviewsMedley"]')

但两者都不起作用

关于如何获得它的任何想法?

标签: python-3.xseleniumselenium-webdriver

解决方案


您在find_element_by_class_nameie中使用了 2 个类,a-size-mediuma-color-baseclass_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

您可以在 xpath 中使用复合类,如下所示

 driver.find_element_by_xpath("//span[@class='a-size-base a-nowrap']").text

在您的情况下会出现一次 require 元素,因此请使用find_element而不是find_elements.


推荐阅读