python-3.x - 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"]')
但两者都不起作用
关于如何获得它的任何想法?
解决方案
您在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
您可以在 xpath 中使用复合类,如下所示
driver.find_element_by_xpath("//span[@class='a-size-base a-nowrap']").text
在您的情况下会出现一次 require 元素,因此请使用find_element
而不是find_elements
.
推荐阅读
- r - 在 R 中创建卡方矩阵
- python - Python CSV 将数字添加到空单元格
- java - 尝试访问部署在 K8s/Argocd 服务器上的 Spring 后端时,“缺少所需的受众”
- mongodb - mongodb不同的查询值
- reactjs - 必须在 React Context 渲染后调用方法
- assembly - x86 Assembly (AT&T):是否有用于确定两个值的最小值/最大值的内置函数?
- python - 将字符串数组转换为日期时间数组
- qt - 最后一个空列填充 QTableView
- dart - 如何为函数参数声明自定义类型?
- php - 如何将 jQuery 变量传递给 PHP?