在Selenium中点击一个link:find_element_by_link_text不起作用

Click on a link in Selenium: find_element_by_link_text doesn't work

我打算通过 selenium 单击 link,但是当我应用 find_element_by_link_text 时它不起作用 如下所示:(URL: https://healthunlocked.com/positivewellbeing )

HTML代码

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

硒代码:

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

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

点击前尝试添加.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

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

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

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

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

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

海狸鼠是一个包装器,可以让您免于重试、休眠(等待)。

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

海狸鼠在 Nuget 上:

PM> Install-Package Coypu

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

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

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

Browser.FindIdEndingWith("Posts").Click();