![](/img/trans.png)
[英]Python selenium webdriver not consistently selecting element even though it's there
[英]Selenium WebDriver cannot click element even though it seems to be visible
在此页面上 ,使用Python 2,使用Firefox的 Selenium,我正在尝试让驱动程序单击以下按钮(放大镜):
<button id="search-btn" type="button" class="header__user-menu-item header__search-btn">
<span class="sr-only">Search</span>
<img src="/sites/default/themes/custom/smp_bootstrap/images/search.svg" class="header__user-menu-icon fa fa-search fa-fw" alt="Search">
</button>
我将以下代码用于元素的XPath, x = '//*[@id="search-btn"]'
:
x = '//*[@id="search-btn"]'
try:
element = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, x)))
except:
print "Element not clickable"
else:
found_element = driver.find_element_by_xpath(x)
try:
found_element.click()
except:
raise
硒的常见的例外EC.element_to_be_clickable
没有标识的元素,也不visibility_of_element_located
也不presence_of_element_located
。
然而,奇怪的是,在某些情况下,驱动程序实际上已经能够识别该元素,然后执行driver.find_element_by_xpath(x)
似乎可以找到XPath和.click()
元素。 那时一切正常。 一秒钟我以为脚本会在页面加载之前快速执行该操作,但是5秒钟WebDriverWait
足以加载页面,在此之前我还有额外的页面加载睡眠。
该元素似乎不在IFrame中。 我已经通过了“接受条件”按钮等。
我正在运行最新版本的Firefox(61.0),Selenium(3.13)和Geckodriver(0.21.0)。
这可能是什么问题?
如果我用By.ID
而不是By.XPATH
获取元素,这行得通,也许您输入了错误的xpath
?
如果使用xpath
也可以x = '//*[@id="search-btn"]'
id = 'search-btn'
element = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.ID, id)))
element.click()
可以使用以下方法来定位<img>
标记,而不是使用<button>
元素进行更细化的处理:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//img[@class='header__user-menu-icon fa fa-search fa-fw' and @alt='Search']"))).click()
使用Firefox作为驱动程序,我能够通过执行JavaScript单击该元素:
driver.execute_script("window.document.getElementById('search-btn').click()")
请注意,以上是非常规措施,不需要使用。 其他答案是正确的,也是通常的做法。
问题在于Selenium驱动程序无法识别XPath元素,这是由于当前版本的geckodriver(0.21.0)与Selenium(3.13.0)结合存在错误 ,请参阅: 出现以下问题时 ,Selenium webdriver管道错误:命令之间的差距?
我降级到geckodriver 0.20.1以避免该问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.