Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

python - How to use find_element_by_link_text() properly to not raise NoSuchElementException?

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>

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")

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...