gpt4 book ai didi

python - Webdriver.get() 不会导航到另一个页面,直到我在调用之前添加等待

转载 作者:太空宇宙 更新时间:2023-11-04 05:28:37 25 4
gpt4 key购买 nike

我有一个 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_istitle_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如果您在内置条件中找不到合适的条件。

关于python - Webdriver.get() 不会导航到另一个页面,直到我在调用之前添加等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37908557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com