【发布时间】:2017-12-29 05:34:24
【问题描述】:
我正在编写一个脚本,以从我必须登录才能使用的站点中提取一些信息。我正在使用 Python 2.7.12 和 Selenium 3.4.3。
#!/usr/bin/python
from selenium import webdriver
browser = webdriver.Firefox(firefox_binary='/usr/bin/firefox', executable_path="./geckodriver")
# Get to the login page
browser.get('https://example.com')
browser.find_element_by_link_text('Application').click()
# Login
browser.find_element_by_id('username').send_keys('notmyusername')
browser.find_element_by_id('password').send_keys('notmypassword')
browser.find_element_by_css_selector('.btn').click()
# Open the application
browser.find_element_by_id('ctl00_Banner1_ModuleList_ctl01_lnkModule').click()
如果我复制这段代码并将其粘贴到 python 控制台中,它会运行良好并转到我想要的页面。但是,当我从终端(Linux Mint 18 上的 bash)运行脚本时,它会出错。这是删除了 try 和 catch 语句的输出:
Traceback (most recent call last):
File "./script.py", line 14, in <module>
browser.find_element_by_id('ctl00_Banner1_ModuleList_ctl01_lnkModule').click()
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 289, in find_element_by_id
return self.find_element(by=By.ID, value=id_)
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 791, in find_element
'value': value})['value']
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 256, in execute
self.error_handler.check_response(response)
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: [id="ctl00_Banner1_ModuleList_ctl01_lnkModule"]
我什至不知道如何解决这个问题。有什么帮助吗?
【问题讨论】:
-
你试过等待吗?
-
@muraliselenium 你的意思是在脚本中等待吗? Selenium 似乎要等到页面加载完毕后再采取任何行动。脚本在无法通过 id 找到元素后出错并停止运行。
-
是的,你说得对。但有时 thread.sleep 会在 java 中有所帮助。所以只是想知道你是否尝试过。
-
@muraliselenium 你完全正确!那解决了它。谢谢,祝您有美好的一天!
-
好。祝你有美好的一天..
标签: python python-2.7 selenium selenium-webdriver