如何正确使用find_element_by_link_text()而不引发NoSuchElementException? [英] How to use find_element_by_link_text() properly to not raise NoSuchElementException?

查看:1410
本文介绍了如何正确使用find_element_by_link_text()而不引发NoSuchElementException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的HTML代码:

I have a HTML code like this:

<div class="links nopreview"><span><a class="csiAction"
href="/WebAccess/home.html#URL=centric://REFLECTION/INSTANCE/_CS_Data/null">Home</a></span>&nbsp;•&nbsp;<span><span><a class="csiAction"
href="/WebAccess/home.html#URL=centric://SITEADMIN/_CS_Site">Setup</a></span>&nbsp;•&nbsp;</span><span><a
title="Sign Out" class="csiAction csiActionLink">Sign Out</a></span></div>

我想单击文本为 Home 的链接.登录后出现此Home链接时,我有这样的代码:

I would like to click on the link that has the text Home. As this Home link appears after login, I have a code like this:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import re

browser = webdriver.Firefox() # Get local session of firefox
browser.get("http://myServer/WebAccess/login.html") # Load App page
elem = browser.find_element_by_name("LoginID") # Find the Login box
elem.send_keys("Administrator")
elem = browser.find_element_by_name("Password") # Find the Password box
elem.send_keys("Administrator" + Keys.RETURN)
#try:
elem = browser.find_element_by_link_text("Home")
elem.click()

登录之前的部分效果很好.但是最后一行却是有问题的

The part till login works great. However the last but one line is problematic

elem = browser.find_element_by_link_text("Home")

它会引发此NoSuchElementException,您可以从HTML代码中看到Home链接.

It raises this NoSuchElementException where the Home link is there as you can see from the HTML code.

raise exception_class(message, screen, stacktrace)
NoSuchElementException: Message: u'Unable to locate element: {"method":"link text","selector":"Home"}' 

请问关于我在做什么错的任何指导?

Any guidance as to what I am doing wrong, please?

推荐答案

您是否尝试过为此添加隐式等待,以使其等待而不是快速运行.

Have you tried adding an implicit wait to this so that it waits instead of running to quickly.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import re

browser = webdriver.Firefox() # Get local session of firefox

browser.implicitly_wait(10) #wait 10 seconds when doing a find_element before carrying on

browser.get("http://myServer/WebAccess/login.html") # Load App page
elem = browser.find_element_by_name("LoginID") # Find the Login box
elem.send_keys("Administrator")
elem = browser.find_element_by_name("Password") # Find the Password box
elem.send_keys("Administrator" + Keys.RETURN)
#try:
elem = browser.find_element_by_link_text("Home")
elem.click()

implicitly_wait调用使浏览器开始轮询,直到该项目在页面上并且可见与之交互为止.

The implicitly_wait call makes the browser poll until the item is on the page and visible to be interacted with.

这篇关于如何正确使用find_element_by_link_text()而不引发NoSuchElementException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆