通过find_element_by_xpath标识的元素返回selenium.common.exceptions.Ele



我点击按钮有问题。如果敌人正在播放,此按钮可以单击,如果敌人出去,则无法单击此按钮 开始 我试过这个:

try:
element= driver.find_element_by_xpath("//button[@class='butwb']")
if element.is_displayed():       
print ("Element found")
else:
print ("Element not found")
except NoSuchElementException:
print("No element found") 

结果:

Element not found

如果我添加element.click()

selenium.common.exceptions.ElementNotVisibleException: Message: element not visible

我做错了什么?

此错误消息...

selenium.common.exceptions.ElementNotVisibleException: Message: element not visible

。意味着您尝试与之交互的元素不可见

下面用于识别元素的代码行是成功的,因为该元素存在于HTML DOM中:

element= driver.find_element_by_xpath("//button[@class='butwb']")

在这一点上值得一提的是,元素的存在意味着元素存在于页面的 DOM 上。这并不能保证元素是可见的(即显示的(或可交互的(即可点击的(。

可见性意味着元素不仅显示,而且具有大于 0 的高度和宽度。

因此is_displayed()该方法返回false并执行else{}块,该块打印:

Element not found

此外,当您调用click()时,会引发以下异常:

selenium.common.exceptions.ElementNotVisibleException: Message: element not visible

可能的原因

  • 您采用的定位器策略无法识别该元素,因为它不在浏览器的视口中。

  • 您采用的定位器策略不能唯一标识HTML DOM中的所需元素,并且当前会找到其他一些隐藏/不可见的元素。

  • 您采用的定位器策略可识别元素,但由于存在属性style="display: none;">,因此不可见。

  • Web元素可能存在于模式对话框中,并且可能无法立即可见/交互。

解决 方案

  • 使用execute_script()方法将元素滚动到视图中,如下所示:

    elem = driver.find_element_by_xpath("element_xpath")
    driver.execute_script("arguments[0].scrollIntoView();", elem);
    

    在这里,您将找到有关使用Selenium在Python中滚动到页面顶部的详细讨论

  • 如果您采用的定位器策略不能唯一标识HTML DOM中的所需元素,并且当前将其他隐藏/不可见元素定位为第一个匹配项,则必须更改定位器策略

  • 如果元素具有属性style="display: none;">,则通过executeScript()方法删除该属性,如下所示:

    elem = driver.find_element_by_xpath("element_xpath")
    driver.execute_script("arguments[0].removeAttribute('style')", elem)
    elem.send_keys("text_to_send");
    
  • 如果该元素在HTML DOM中不存在/可见/可交互,请诱导WebDriverWait,并将expected_conditions设置为正确的方法,如下所示:

    • 等待presence_of_element_located

      element = WebDriverWait(driver, 20).until(expected_conditions.presence_of_element_located((By.XPATH, "element_xpath']")))
      
    • 等待visibility_of_element_located

      element = WebDriverWait(driver, 20).until(expected_conditions.visibility_of_element_located((By.CSS_SELECTOR, "element_css")
      
    • 等待element_to_be_clickable

      element = WebDriverWait(driver, 20).until(expected_conditions.element_to_be_clickable((By.LINK_TEXT, "element_link_text")))
      

在与Kuncioso交谈并进入游戏后,我们发现有两个按钮与他的定位器匹配,第一个是隐藏的。使用下面的代码单击第二个按钮(他想要的按钮(解决了问题。

driver.find_elements_by_xpath("//button[@class='butwb']")[1].click()

最新更新