【问题标题】:Click on a link in Selenium: find_element_by_link_text doesn't work单击 Selenium 中的链接:find_element_by_link_text 不起作用
【发布时间】:2021-02-24 11:48:27
【问题描述】:

我将通过 selenium 点击一个链接,但是当我应用 find_element_by_link_text 时它不起作用 如下:(网址:https://healthunlocked.com/positivewellbeing

HTML 代码

<a class href="/positivewellbeing/posts">Posts</a>

硒代码:

driver.find_element_by_link_text('Posts').click()

我没有任何错误,但此代码行没有运行或工作

【问题讨论】:

    标签: python selenium selenium-webdriver web-scraping web-crawler


    【解决方案1】:

    点击前尝试添加.element_to_be_clickable

    wait = WebDriverWait(driver, 20)
    wait.until(EC.element_to_be_clickable((By.LINK_TEXT, 'Posts'))).click()
    
    #update here
    wait.until(EC.url_to_be('https://healthunlocked.com/positivewellbeing/posts'))
    print(driver.current_url)
    

    以下导入:

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

    根据您的cmets,如果您想等待url更改为您想要的方式,请使用EC.url_to_be。因为time.sleep (...)是不好的方式,请看上面更新的代码。

    在此处查看有关 expected_conditions 的更多信息:

    https://selenium-python.readthedocs.io/api.html#expected-conditions-support

    【讨论】:

    • 非常感谢您的帮助。我按照你说的做了,但还是不行。为了检查它是否有效,我输入了“ print(driver.current_url)。它应该返回“healthunlocked.com/positivewellbeing/posts”但它返回“healthunlocked.com/positivewellbeing
    • @TaherehMaghsoudi 请确保在点击帖子链接之前关闭“我们使用 cookie”通知
    • 是的,一开始我是通过以下代码行:#close cookies thing driver.find_element_by_id('ccc-notify-accept').click()
    • 我可以通过设置 time.sleep 来解决它。 “driver.find_element_by_link_text('Posts').click() time.sleep(3) print (driver.current_url)” 现在可以了。谢谢大家
    • @TaherehMaghsoudi 很高兴它起作用了,但是如果您想等到 url 更改,请参阅上面的更新代码。希望这会有所帮助。
    【解决方案2】:

    如果您使用的是 .Net,您可以尝试在您的项目中使用 Coypu 库:

    https://github.com/featurist/coypu https://www.nuget.org/packages/Coypu/

    Coypu 它是一个包装器,可以让你免于重试、休眠(等待)。

    它支持 .Net 中的浏览器自动化,以帮助使测试具有可读性、健壮性、编写速度快且与 UI 的联系更少。如果您的测试充斥着休眠、重试、复杂的 XPath 表达式和 ID,那么 Coypu 可能会有所帮助。

    Coypu 在 Nuget:

    PM> Install-Package Coypu
    

    我在一个项目中工作,我们使用 C# 和 Selenium 开发了大约 3k 个自动化测试,如果没有 Coypu,我的生活会有点悲惨。

    使用 Coypu 时,您的代码看起来相同,但睡眠将由库自动处理,它对用户是透明的:

    Browser.FindXPath("//*[contains(text(), 'Posts')]").Click();
    
    Browser.FindIdEndingWith("Posts").Click();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-12
      • 1970-01-01
      • 1970-01-01
      • 2016-05-18
      • 2016-08-22
      • 2014-01-12
      • 2015-04-13
      相关资源
      最近更新 更多