单击Selenium中的链接:按链接查找元素文本不起作用

2024-06-06 03:41:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我打算通过selenium单击一个链接,但当我应用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()

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


Tags: 代码texthttpscomurlby链接html
2条回答

在单击之前,请尝试添加.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/coypuhttps://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();

相关问题 更多 >