如何使用 Selenium 和 Python 调用函数之前等待特定 URL 加载

Hol*_*ger 6 python url selenium webdriver webdriverwait

这是我第一次在 stackoverflow 上发帖,我对 Selenium 和 Python 还有些陌生。

当 URL 等于 fx: https://www.example.com时,我不希望运行函数。

我在另一个讨论中读过 这个答案,但我不太明白发生了什么。

我希望您能抽出时间回答我的问题。

好的,所以我刚刚尝试过这个:

driver.get('https://www.google.com')
time.sleep(4)
driver.get('https://www.stackoverflow.com')

if WebDriverWait(driver, 10).until(EC.url_to_be('https://stackoverflow.com')):
    print('Desired url was rendered within allocated time')
else:
    print('Desired url was not rendered within allocated time')
Run Code Online (Sandbox Code Playgroud)

但这没有用。有任何想法吗?
控制台说

Traceback (most recent call last):
  File "/Users/holger/PycharmProjects/waitTest/wait.py", line 15, in <module>
    if WebDriverWait(browser, 10).until(EC.url_to_be('https://www.stackoverflow.com')):
  File "/Users/holger/PycharmProjects/waitTest/venv/lib/python3.8/site-packages/selenium/webdriver/support/wait.py", line 80, in until
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: 
Run Code Online (Sandbox Code Playgroud)

Deb*_*anB 6

如果您的用例是在 url 等于时运行一个函数,https://www.example.com您将引发WebDriverWait与以下预期条件之一的结合:

然而,WebDriverWait与上面提到的结合起来可能无法保证DOM Treeexpected_conditions中的所有元素都被完全加载。

您可以在我们是否有任何通用函数来检查 Selenium 中页面是否已完全加载中找到详细讨论


更新

要在WebDriverWait返回时运行函数,True可以使用以下解决方案:

try:
    WebDriverWait(driver, 30).until(EC.url_to_be("https://www.example.com")))
    print("Desired url was rendered with in allocated time")
    # now you can call the method/function
    # test_me("Holger")
except TimeoutException:
    print("Desired url was not rendered with in allocated time")
Run Code Online (Sandbox Code Playgroud)

注意:您必须添加以下导入:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
Run Code Online (Sandbox Code Playgroud)

参考

您可以在以下位置找到相关的详细讨论:

  • 您无缘无故地从文档中转储了 EC 的所有与 url 相关的方法,然后使用了 OP 所做的相同的 EC...这应该如何解决问题? (3认同)

归档时间:

查看次数:

6700 次

最近记录:

6 年 前