【问题标题】:What is the best way to check URL change with Selenium in Python?在 Python 中使用 Selenium 检查 URL 更改的最佳方法是什么?
【发布时间】:2016-07-18 21:46:19
【问题描述】:

所以,我想做的是在特定网页上运行一个函数(与我的正则表达式匹配)。

现在我每秒都在检查它并且它有效,但我确信有更好的方法(因为它正在通过获取请求淹没该网站)。

while flag:
    time.sleep(1)
    print(driver.current_url)
    if driver.current_url == "mydesiredURL_by_Regex":
        time.sleep(1)
        myfunction()

我想通过WebDriverWait 以某种方式做到这一点,但不确定如何。

【问题讨论】:

  • 根据official documentation,这几乎正是使用WebDriverWait 所做的。默认情况下,它每 0.5 秒检查一次条件。一个优点是,在 WebDriverWait 中使用单行代码比在任何其他方法中使用 >5 行代码更具可读性。

标签: python regex selenium url


【解决方案1】:

我想用 WebDriverWait 以某种方式做到这一点

没错。首先,看看built-in Expected Conditions是否可以解决这个问题:

  • 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"))

如果没有,您可以随时创建custom Expected Condition 来等待 url 匹配所需的正则表达式。

【讨论】:

  • 又得到了一个,有点棘手的问题。那超时是必要的吗?我的意思是,也许该脚本必须等待大约 30 分钟才能达到预期的条件/正则表达式,是否也有一种好方法来处理它?谢谢
  • @gyula 我记得,超时是必需的..要么将其设置为一个较大的值,要么使用“while true”方法..
【解决方案2】:

这就是我最终实现它的方式。很适合我:

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 5)
desired_url = "https://yourpageaddress"

def wait_for_correct_current_url(desired_url):
    wait.until(
        lambda driver: driver.current_url == desired_url)

【讨论】:

【解决方案3】:

要真正知道 URL 已更改,您需要知道旧的。使用WebDriverWait,Java 中的实现类似于:

wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.not(ExpectedConditions.urlToBe(oldUrl)));

我知道这个问题是针对 Python 的,但它可能很容易翻译。

【讨论】:

    【解决方案4】:

    这是一个使用WebdriverWaitexpected_conditions 的示例:

    from selenium import webdriver
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC 
    
    url = 'https://example.com/before'
    changed_url = 'https://example.com/after'
    
    driver = webdriver.Chrome()
    driver.get(url)
    
    # wait up to 10 secs for the url to change or else `TimeOutException` is raised.
    WebDriverWait(driver, 10).until(EC.url_changes(changed_url))
    

    【讨论】:

      【解决方案5】:

      使用 url_matches Link 将正则表达式模式与 url 匹配。它确实re.search(pattern, url)

      from selenium import webdriver
      import re
      from selenium.webdriver.support import expected_conditions as EC
      from selenium.webdriver.support.ui import WebDriverWait
      
      pattern='https://www.example.com/'
      driver = webdriver.Chrome()
      wait = WebDriverWait(driver,10)
      
      wait.until(EC.url_matches(pattern))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-25
        • 1970-01-01
        • 2015-10-13
        • 1970-01-01
        • 2015-09-16
        • 2021-08-05
        • 1970-01-01
        • 2013-02-21
        相关资源
        最近更新 更多