【问题标题】:Webdriver.get() will not navigate to another page until I add wait before the callWebdriver.get() 在调用前添加等待之前不会导航到另一个页面
【发布时间】:2016-06-19 14:57:20
【问题描述】:

我有一个 Python 3.5 脚本,它基本上登录到一个网站(并在登录后被重定向),然后导航到它实际执行工作的另一个页面。如果我在登录后立即运行webdriver.get() 到第二页,它不会导航到目标位置并停留在我登录后它被重定向到的页面上。但是如果我放置一个断点或只是time.sleep(5) -它打开得很好。我在 C# 代码中发现了this 问题,建议在其中添加异步等待。有没有 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)

【问题讨论】:

    标签: python python-3.x selenium selenium-webdriver


    【解决方案1】:

    您需要应用Explicit WaitsWebDriverWait 类的概念。您只需要选择要等待的预期条件。听起来 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

    【讨论】:

    • 确实,等标题就解决了! Selenium 文档 says“WebDriver 将等待页面完全加载(即 onload 事件已触发),然后再将控制权返回给您的测试或脚本,这对我来说仍然很奇怪。”所以我认为这就足够了......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-25
    • 2016-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-29
    相关资源
    最近更新 更多