python - Selenium 解析整个文档而不是 webelement
问题描述
这个问题真的让我发疯了!这是我的代码:
list_divs = driver.find_elements_by_xpath("//div[@class='myclass']")
print(f'Number of divs found: {len(list_divs)}') #Correct number displayed
for art in list_divs:
mybtn = art.find_elements_by_xpath('//button') #There are 2 buttons in each div
print(f'Number of buttons found = {len(mybtn)}') #Incorrect number (129 instead of 2)
mybtn[2].click() #Wrong button clicked!
单击的按钮不在艺术Html中,而是在网页的开头!!!似乎 Selenium 正在解析整个文档而不是 webelement艺术......我已经打印了可变艺术的 outerHTML并且它是正确的:只有包含 2 个按钮的 div 代码!!!!那么为什么find_elements_by_xpath()
应用于webelement艺术的功能不是解析div而是解析整个html页面????!!!对我来说完全无法理解!
解决方案
因为您使用mybtn = art.find_elements_by_xpath('//button')
where会//button
忽略您的搜索上下文,因为它从//
. 将其更改为:
mybtn = art.find_elements_by_xpath('.//button')
推荐阅读
- android - Android Espresso:当视图显示在屏幕上时如何执行操作?
- django - Django REST 未正确呈现表单
- git - 除非我克隆,否则我无法获得 origin/master
- python-3.x - BGP 会话建立期间出错(打开确认状态)
- firebase - Firestore 同步到底有什么作用?
- arrays - 如何调整可迭代数组的功能?
- r - 如何在 R Markdown 中编写这个复杂的公式?
- sql-server - SQL_Hungarian_CP1250_CI_AS 表现为区分大小写
- r - dplyr 过滤器仅获取其中一个组采用的值
- django - 从国家字段中保存国家名称