【问题标题】:Find an element by part of the href attribute通过 href 属性的一部分查找元素
【发布时间】:2019-09-30 03:24:01
【问题描述】:

我正在尝试自动打开页面上的任何联系人菜单: 例如,我要去“http://www.bawnlodge.co.uk/”页面 - 然后我想点击“联系人”标签

ATM 我尝试了各种方法,例如:

driver.find_element_by_xpath("//*[contains(text(), 'onta')]").click()

driver.find_element_by_xpath('//a[contains(@href, "onta")]').click()

(很少有类似的)

但是到目前为止,我无法点击该元素

如果有人能解释我为什么在这里失败,我将不胜感激:/

【问题讨论】:

    标签: python-3.x selenium xpath css-selectors webdriverwait


    【解决方案1】:

    您可以使用更快的类或 id css 选择器

    WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '.menu-item-26 a'))).click()
    

    WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#menu-item-100 a'))).click()
    

    您也可以简单地将字符串 "contact" 连接到 "http://www.bawnlodge.co.uk/" 和 .get 上。多词选项卡名称由“-”连接,例如lodge-bar-and-kitchen。一切都是小写的。

    【讨论】:

      【解决方案2】:

      尝试 WebDriverWait 并遵循定位器策略。

      element=WebDriverWait(driver,30).until(EC.element_to_be_clickable((By.XPATH,'//div[@class="right"]//ul[@id="menu-header-right"]//li/a[contains(.,"Contact")]')))
      element.click()
      

      您需要有以下导入才能在上面的代码中工作。

      from selenium import webdriver
      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.support import expected_conditions as EC
      from selenium.webdriver.common.by import By
      

      【讨论】:

        【解决方案3】:

        要使用 href 属性的一部分在文本为 CONTACT 的元素上调用 click(),您需要为所需的 element_to_be_clickable() 诱导 WebDriverWait 并且您可以使用以下任一Locator Strategies

        • 使用CSS_SELECTOR

          WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.container a[href*='contact']"))).click()
          
        • 使用XPATH

          WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='container']//a[contains(@href, 'contact')]"))).click()
          
        • 注意:您必须添加以下导入:

          from selenium.webdriver.support.ui import WebDriverWait
          from selenium.webdriver.common.by import By
          from selenium.webdriver.support import expected_conditions as EC
          

        【讨论】:

          猜你喜欢
          • 2018-12-24
          • 2015-04-18
          • 1970-01-01
          • 2018-10-20
          • 2012-07-08
          • 1970-01-01
          • 2020-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多