[英]Why does my Selenium code work in the Python Shell but not from a file?
Here's my code: 这是我的代码:
from selenium import webdriver
browser = webdriver.Firefox()
browser.get('https://mail.yahoo.com')
emailElem = browser.find_element_by_id('login-username')
emailElem.send_keys('myemail@sbcglobal.net')
emailElem.submit()
passwordElem = browser.find_element_by_id('login-passwd')
passwordElem.send_keys('password')
signInLink = browser.find_element_by_id('login-signin')
signInLink.click()
When I type each line individually in the shell, it works fine and I get logged in to my email, however, when I run the script from a file, it crashes on line 8. Error message is "Unable to locate element [id="login-passwd"]. No idea why it works in the shell though. In there, it obviously does find that field. See screenshot below so you can see how it works on the shell (left), but crashes when run from a file (right). Oh and bonus points if you can tell my why using emailElem.submit() works, but using passwordElem.submit() doesn't. I have to find the button and click that link. If I put passwordElem.submit() the page resets and password field becomes blank. No idea why 当我在外壳中分别键入每一行时,它可以正常工作,并且可以登录我的电子邮件,但是,当我从文件运行脚本时,它在第8行崩溃。错误消息是“无法找到元素[id = “” login-passwd“]。虽然不知道为什么它可以在shell中工作,但显然在那里它确实找到了该字段。请参见下面的屏幕截图,以便您可以看到它如何在shell上工作(左侧),但是当从外壳程序运行时会崩溃文件(右)。哦,如果您能告诉我为什么使用emailElem.submit()可以,但是使用passwordElem.submit()却行不通,则需要加分,我必须找到该按钮并单击该链接。提交()页面重置,密码字段变为空白。不知道为什么
The script runs faster than pasting each line in the shell - Since the element is created dynamically in the page, when pasting each line you gave enough time for the browser to run the javascript code and generate the element. 该脚本的运行速度比粘贴外壳程序中的每一行都要快-由于该元素是在页面中动态创建的,因此粘贴每一行时,您给了足够的时间让浏览器运行javascript代码并生成该元素。
When running the script, the line that searches for the element is reached before the element is created, so you get the error. 运行脚本时,在创建元素之前已到达搜索元素的行,因此会出现错误。
There are many possible solutions, which usually involve using a selenium wait method , or time.sleep
, or a combination of those. 有许多可能的解决方案,通常涉及使用硒等待方法 ,
time.sleep
或它们的组合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.