【问题标题】:How to set the xpath for a element in html using python selenium webdriver如何使用python selenium webdriver为html中的元素设置xpath
【发布时间】:2018-06-05 04:57:10
【问题描述】:
<div id="div_1" class="info-container">
  <div class="name" data-toggle="dropdown"><div>
  <div class="name" data-toggle="dropdown"><div>
  <div id="div_2" class="btn-group user-helper-dropdown">
     <i  class="material-icons" data-toggle="dropdown" 
      aria-haspopup="true" aria-expanded="true"></i>
     <ul id="div_3" class="dropdown-menu pull-right">
       <li><a href="/profile/user/view"><i class="material
              icons">person</i>Profile</a></li>
       <li role="seperator" class="divider"></li>
       <li id="sgn_out"><a id="sign_out_button" href="/sign-out"><i
           class="material-icons">input</i>Sign Out</a></li>
     </ul>
  </div>
<div>

您好,我无法在 Python 的 selenium webdriver 中找到具有 id='sign_out_button' 的标签的 XPath

这是我尝试过的:

driver.find_element_by_xpath("//div[@id='div_1']/div[@id='div_2']/ul[@id='div_3']/li[@id='sgn_out']/a")

但它给了我这样的错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element:
Unable to locate element: 
{"method":"xpath","selector":"//div[@id='div_1']/div[@id='div_2']/ul[@id='div_3']/li[@id='sgn_out']/a"}

【问题讨论】:

  • 该 html 中没有 &lt;div id="div_1" ...&gt; 元素。
  • @JohnGordon 我的错。现在已经修复了
  • driver.find_element_by_xpath("//a[@id='sign_out_button']") 应该足以找到退出链接。或者干脆driver.find_element_by_id("sign_out_button")
  • driver.find_element_by_id("sign_out_button")driver.find_element_by_link_text("Sign Out") 是否有同样的异常?
  • @Andersson 是的,对于您在这里提到的所有类型,我都遇到了同样的错误

标签: python html selenium-webdriver


【解决方案1】:

根据您共享的 HTML,在带有 id='sign_out_button' 的元素上调用 click(),因为它是一个下拉项,您必须为 WebDriverWait 诱导 可点击的元素如下:

  • CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "ul.dropdown-menu#div_3 li#sgn_out>a#sign_out_button"))).click()
    
  • XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//ul[@class='dropdown-menu pull-right' and @id='div_3']//li[@id='sgn_out']/a[@id='sign_out_button']"))).click()
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-28
    • 2013-01-13
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 2015-10-09
    • 2017-09-14
    • 1970-01-01
    相关资源
    最近更新 更多