【问题标题】:FInd Element and Click. If Not Found goto next page查找元素并单击。如果未找到转到下一页
【发布时间】:2021-09-12 14:19:48
【问题描述】:

您好,我在第 1 页中的元素有以下代码。

<span _ngcontent-iyc=""class="ng-star-inserted">ELEMENT 1</span>
<span _ngcontent-iyc=""class="ng-star-inserted">ELEMENT 2</span>
<span _ngcontent-iyc=""class="ng-star-inserted">ELEMENT 3</span>
<span _ngcontent-iyc=""class="ng-star-inserted">ELEMENT 4</span>

同样,我还有 4 个包含不同元素的页面。

我需要的是使用 selenium python 找到一个元素,如果该元素存在于该页面中,则单击它。否则点击下一页,在那里搜索元素,直到找到元素。

我试过的代码是:

elxpath = "//span[contains(text(),'Element 20')]"
while True:
    time.sleep(5)

        if (driver.find_element_by_xpath(elxpath)):
            driver.find_element_by_xpath(elxpath).click()
            break
        else:
            driver.find_element_by_xpath("xpath to goto next page").click()
            break

但此代码适用于第一页中的元素。如果条件为假,则不点击下一页。

我得到的错误: 消息:没有这样的元素:无法找到元素:{"method":"xpath","selector":"//span[contains(text(),'Element 20')]"}

还有其他方法可以做到这一点吗? 谢谢

【问题讨论】:

    标签: python selenium xpath selenium-chromedriver browser-automation


    【解决方案1】:

    你可以这样做

    
    elxpath = "//span[contains(text(),'Element 20')]"
    while True:
        time.sleep(5)
        try:
            driver.find_element_by_xpath(elxpath).click()
            break
        except Exception:
            driver.find_element_by_xpath("xpath to goto next page").click()
    

    【讨论】:

      【解决方案2】:

      find_element_by_ 将返回该元素,如果找不到该元素,NoSuchElementException 将抛出,if 在这里不起作用。

      使用find_elements_by_获取元素列表并检查是否为空

      elements = driver.find_elements_by_xpath(elxpath)
      if elements:
          elements[0].click()
      

      【讨论】:

      • 非常感谢...!! find_elements_by_ 工作。
      【解决方案3】:

      更好地使用tryexcept

      from selenium.common.exceptions import NoSuchElementException
      
      elxpath = "//span[contains(text(),'Element 20')]"
      while True:
          time.sleep(5)
      
              try:
                  driver.find_element_by_xpath(elxpath).click()
                  break
              except NoSuchElementException:
                  driver.find_element_by_xpath("xpath to goto next page").click()
                  break
             
      

      【讨论】:

        猜你喜欢
        • 2020-03-01
        • 2015-10-07
        • 1970-01-01
        • 2021-08-19
        • 1970-01-01
        • 1970-01-01
        • 2017-11-19
        • 2019-11-21
        • 1970-01-01
        相关资源
        最近更新 更多