我有一个 Python 3.5 脚本,它基本上登录到一个网站(并在登录后被重定向),然后导航到它实际完成工作的另一个页面。如果我在登录后立即运行 webdriver.get() 到第二页,它不会导航到目标位置并停留在我登录后重定向到的页面上。但是如果我放置一个断点或只是 time.sleep(5) - 它可以正常打开。我找到了 this C# 代码的问题,建议在其中添加异步等待。是否有 Pythonic 的方法来解决它?
我的引用代码:
# underneath is webdriver.Chrome() wrapped up in some exception handling
mydriver = get_web_driver()
# do the first get, wait for the form to load, then fill in the form and call form.submit()
login(mydriver, login_page, "username", "password")
# perform the second get() with the same webdriver
open_invite_page(mydriver, group_invite_page)
请您参考如下方法:
你需要应用Explicit Waits的概念和 WebDriverWait 类。您只需要选择要等待的预期条件。听起来 title_is 和 title_contains 可能适用于您的情况:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
login(mydriver, login_page, "username", "password")
# wait for invite page to be opened
wait = WebDriverWait(mydriver, 10)
wait.until(
EC.title_is("Invite Page") # TODO: change to the real page title
)
open_invite_page(mydriver, group_invite_page)
请注意,有多个内置的预期条件。例如,您可以等待特定元素在邀请页面上出现、可见或可点击。而且,您可以创建 custom Expected Conditions如果您在内置条件中找不到合适的条件。
