【问题标题】:How to click on a <a href=""> using Selenium in Python)如何在 Python 中使用 Selenium 点击 <a href="">)
【发布时间】:2021-01-08 16:44:47
【问题描述】:

我正在尝试点击此链接:

<a href="updating/login.php" target="_top">Login</a>

使用 Python 使用 Selenium。我尝试使用此代码通过文本查找和单击元素,但它不起作用:

elem = rd.driver.find_element_by_link_text("Login")
elem.click() 

如何做到这一点?

【问题讨论】:

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


【解决方案1】:

要点击WebElement,文本为Login,您需要为element_to_be_clickable()诱导WebDriverWait,您可以使用以下Locator Strategies之一:

  • 使用LINK_TEXT

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "Login"))).click()
    
  • 使用CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[href='updating/login.php']"))).click()
    
  • 使用XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@href='updating/login.php' and text()='Login']"))).click()
    
  • 注意:您必须添加以下导入:

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

【讨论】:

  • 我试过你的方法,但我得到了这个错误:Traceback (most recent call last): File "C:/Users/ta-ph/Documents/Sites for success test/peopleFinder.py", line 13, in &lt;module&gt; WebDriverWait(rd.driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//a[@href='updating/login.php' and text()='Login']"))).click() File "C:\Users\ta-ph\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until raise TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message:
猜你喜欢
  • 2022-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-14
  • 2023-01-08
  • 2023-01-25
  • 2019-08-04
相关资源
最近更新 更多