以下是我的脚本,它运行正常,但不符合我的要求
from selenium import webdriver
browser = webdriver.Firefox()
browser.get('https://somewebsite.com/')
#nextline of script
在上面的示例中,它打开浏览器并立即转到下一步。 我希望脚本等到我手动关闭浏览器并转到下一步 (因为我想登录并从服务器下载一些文件并转到下一步)
答案 0 :(得分:1)
我同意alecxe您通常应该自动完成整个过程。但是,在某些情况下,您可能正在编写“一次性代码”或概念验证,其中可能有利于手动控制部分流程。如果我发现自己处于这样的境地,我会做这样的事情:
import time
from selenium import webdriver
browser = webdriver.Firefox()
browser.get('https://google.com/')
try:
while True:
# This will fail when the browser is closed.
browser.execute_script("")
time.sleep(0.2)
# Setting such a wide exception handler is generally not advisable but
# I'm not convinced there is a definite set of exceptions that
# Selenium will stick to if it cannot contact the browser. And I'm not
# convinced the set cannot change from release to release.
except:
has_quit = False
while not has_quit:
try:
# This is to allow Selenium to run cleanup code.
browser.quit()
has_quit = True
except: # See comment above regarding such wide handlers...
pass
# Continue with the script...
print "Whatever"
对browser.quit()
的调用是为了让Selenium可以自行清理。这对Firefox来说非常重要,因为Selenium会创建一堆临时文件,可以填满/tmp
(在Unix类型的系统上,我不知道Selenium放在哪里随着时间的推移,Windows系统上的文件)。理论上,Selenium应该能够优雅地处理在browser.quit()
被调用之前浏览器不再存在的情况,但是我发现没有捕获到内部异常并且browser.quit()
会立即失败的情况。 (顺便说一句,这支持了我对Selenium可以引发的异常集的评论,如果浏览器不清楚的话:甚至Selenium也不知道Selenium会引发什么异常,这就是为什么browser.quit()
有时会失败的原因。)重复直到它成功的电话似乎有效。
请注意,只要您关闭浏览器,browser
就会无效。如果你想做更多浏览器,你必须生成一个新的浏览器。
此外,通常无法区分关闭浏览器的用户和浏览器崩溃。
答案 1 :(得分:-1)
如果页面未完全加载,您可以随时等待页面上的特定元素显示,例如,下载按钮。 或者您可以等待加载所有JavaScript。
wait.until( new Predicate<WebDriver>() {
public boolean apply(WebDriver driver) {
return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
}
}
);