【问题标题】:How to click href javascript:void(0) and hidefocus=true with selenium python?如何使用 selenium python 单击 href javascript:void(0) 和 hidefocus=true?
【发布时间】:2019-07-13 20:49:17
【问题描述】:

如何点击href? 我试过了

driver.find_element_by_xpath("/div/a[@id='switcher_plogin']")

我收到这样的错误: 我会很感激任何帮助。谢谢。

【问题讨论】:

  • 请阅读为什么a screenshot of code is a bad idea。粘贴代码并正确格式化。
  • 按 id 使用,这里不需要 XPath。它在 IFRAME 中吗?您是否尝试过添加等待点击?

标签: python selenium xpath css-selectors webdriverwait


【解决方案1】:

点击链接 使用WebDriverWaitelement_to_be_clickable 以及以下选项。

Xpath

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH,"//div[@id='bottom_qlogin']/a[@id='switcher_plogin']"))).click()

CSS 选择器

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"#bottom_qlogin #switcher_plogin"))).click()

您需要导入以下代码才能执行上述代码。

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

【讨论】:

    【解决方案2】:
    1. 确保链接不属于iframe,否则您必须先调用WebDriver.switch_to_frame 函数才能将上下文更改为链接所在的iframe
    2. 确保链接不属于Shadow DOM,否则您必须首先使用execute_script 函数定位相关的ShadowRoot 元素,将结果转换为WebElement 并使用WebElement 的find() 函数定位链接
    3. 可能是链接没有立即出现在DOM 中,因此您可能需要介绍Explicit Wait
    4. 如果没有其他元素具有ID attributeswitcher_plogin,您可能需要重新考虑locator strategy 并坚持使用ID 而不是XPath。

    建议的代码更改:

    替换这个:

    driver.find_element_by_xpath("/div/a[@id='switcher_plogin']")
    

    用这个:

    WebDriverWait(driver, 10).until(expected_conditions.presence_of_element_located((By.ID, "switcher_plogin")))
    

    参考资料:

    【讨论】:

      【解决方案3】:

      所需的元素是启用了JavaScript 的元素,因此要在需要为所需element_to_be_clickable() 诱导WebDriverWait 的元素上使用click(),您可以使用以下任一解决方案:

      • 使用CSS_SELECTOR

        WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.link#switcher_plogin"))).click()
        
      • 使用XPATH

        WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='link' and @id='switcher_plogin']"))).click()
        
      • 注意:您必须添加以下导入:

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

      注意:您可以在Selenium “selenium.common.exceptions.NoSuchElementException” when using Chrome找到相关讨论

      【讨论】:

        猜你喜欢
        • 2016-06-08
        • 2013-04-24
        • 2020-11-24
        • 1970-01-01
        • 1970-01-01
        • 2017-06-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多