在 Python 中使用 Selenium 检查 URL 更改的最佳方法是什么? [英] What is the best way to check URL change with Selenium in Python?
问题描述
所以,我想做的是在特定网页上运行一个函数(与我的正则表达式匹配).
So, what's I want to do is to run a function on a specific webpage (which is a match with my regex).
现在我每秒钟都在检查它并且它有效,但我确信有更好的方法(因为它正在通过获取请求淹没该网站).
Right now I'm checking it every second and it works, but I'm sure that there is a better way (as it's flooding that website with getting requests).
while flag:
time.sleep(1)
print(driver.current_url)
if driver.current_url == "mydesiredURL_by_Regex":
time.sleep(1)
myfunction()
我想用 WebDriverWait
以某种方式做到这一点,但不确定如何做.
I was thinking to do that somehow with WebDriverWait
but not really sure how.
推荐答案
我想通过 WebDriverWait 以某种方式做到这一点
I was thinking to do that somehow with WebDriverWait
没错.首先,看看内置预期条件是否可以解决这个问题:
Exactly. First of all, see if the built-in Expected Conditions may solve that:
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
wait = WebDriverWait(driver, 10)
wait.until(EC.title_is("title"))
wait.until(EC.title_contains("part of title"))
如果没有,您始终可以创建一个自定义预期条件以等待 url 匹配所需的正则表达式.
If not, you can always create a custom Expected Condition to wait for url to match a desired regular expression.
这篇关于在 Python 中使用 Selenium 检查 URL 更改的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!