首页 > 解决方案 > 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页面????!!!对我来说完全无法理解!

标签: pythonselenium

解决方案


因为您使用mybtn = art.find_elements_by_xpath('//button')where会//button忽略您的搜索上下文,因为它从//. 将其更改为:

mybtn = art.find_elements_by_xpath('.//button')

推荐阅读