【问题标题】:Conditional selection of elements in Selenium webdriver in PythonPython中Selenium webdriver中元素的条件选择
【发布时间】:2020-03-13 07:18:52
【问题描述】:

我面临这样一种情况,即模态有时有一个用于登录 Facebook 的所需按钮,有时我必须单击“更多选项”才能访问 Facebook 按钮。另一个障碍是more_options_btn 的 xpath 与称为“登录失败?”的 xpath 相同。所以我添加了一个[contains(text(),"More Options")],但我不确定这里的语法并且在文档中找不到正确的方法。在任何情况下它都会抛出一个错误,这可能是由于button 元素没有文本,而是像button > span > text 一样嵌套

请记住,我想让我的解决方案尽可能动态和健壮,但对 Selenium 还没有很多经验。

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(ChromeDriverManager().install())

driver.get('http://localhost:3000/')

try:
    fb_btn = driver.find_element_by_xpath(
        '//*[@id="modal-manager"]/div/div/div/div/div[3]/span/div[2]/button')
    fb_btn.click()
except:
    more_options_btn = driver.find_element_by_xpath(
        '//*[@id="modal-manager"]/div/div/div/div/div[3]/span/button[contains(text(),"More Options")]')
    more_options_btn.click()

    fb_btn = driver.find_element_by_xpath(
        '//*[@id="modal-manager"]/div/div/div/div/div[3]/span/div[2]/button')
    fb_btn.click()

【问题讨论】:

  • 请贴出相关的HTML代码

标签: python-3.x selenium google-chrome selenium-webdriver


【解决方案1】:

尝试将xpath更改为:

//*[@id="modal-manager"]/div/div/div/div/div[3]/span/button[contains(.,"More Options")]

它可以找到'button'的子节点包含文本。

【讨论】:

    【解决方案2】:

    您可以在 xpath | 中使用 OR 运算符来匹配您的 xpath 与多个条件。我建议使用相对 xpath 而不是绝对路径。

    由于你的 xpath 太长,所以它看起来像 OR 条件

    //*[@id="modal-manager"]/div/div/div/div/div[3]/span/div[2]/button | //*[@id="modal-manager"]/div/div/div/div/div[3]/span/button[contains(text(),"More Options")]
    

    【讨论】:

      【解决方案3】:

      结合上面的输入,我设法让它工作。我摆脱了很多长的xpath。这样做的好处是,如果按钮的顺序发生变化,我的代码仍然可以工作。但是,如果按钮的文本发生更改,它仍然会中断,因此这是一种妥协。结果如下:

      from time import sleep
      
      from selenium import webdriver
      from selenium.common.exceptions import NoSuchElementException
      from webdriver_manager.chrome import ChromeDriverManager
      
      driver = webdriver.Chrome(ChromeDriverManager().install())
      
      driver.get('http://localhost:3000/')
      sleep(5)
      
      try:
          fb_btn = driver.find_element_by_xpath(
              "//*/button[contains(.,'Log in with Facebook')]").click()
      except NoSuchElementException:
      
          more_options_btn = driver.find_element_by_xpath(
              "//*[contains(text(), 'More Options')]")
          more_options_btn.click()
          fb_btn = driver.find_element_by_xpath(
              '//*/button[contains(.,"Log in with Facebook")]')
          fb_btn.click()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多