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)
如果您的用例是在 url 等于时运行一个函数,https://www.example.com您将引发WebDriverWait与以下预期条件之一的结合:
url_changes(url):期望检查当前 url,该 url 不能完全匹配。
WebDriverWait(driver, 30).until(EC.url_changes("https://www.example.com"))
Run Code Online (Sandbox Code Playgroud)url_contains(url):期望当前页面的 URL 包含特定文本。
WebDriverWait(driver, 30).until(EC.url_contains("example"))
Run Code Online (Sandbox Code Playgroud)url_matches(pattern):期望 URL 匹配特定的正则表达式。
WebDriverWait(driver, 30).until(EC.url_matches("a_matching_pattern_of_the_expected_url"))
Run Code Online (Sandbox Code Playgroud)url_to_be(url):期望当前页面的 URL 是一个特定的 url。
WebDriverWait(driver, 30).until(EC.url_to_be("https://www.example.com"))
Run Code Online (Sandbox Code Playgroud)注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
Run Code Online (Sandbox Code Playgroud)然而,WebDriverWait与上面提到的结合起来可能无法保证DOM Treeexpected_conditions中的所有元素都被完全加载。
要在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)
您可以在以下位置找到相关的详细讨论:
| 归档时间: |
|
| 查看次数: |
6700 次 |
| 最近记录: |