What is the best way to check URL change with Selenium in Python?

前端 未结 5 2005
我在风中等你
我在风中等你 2020-12-10 15:42

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

相关标签:
5条回答
  • 2020-12-10 15:47

    Use url_matches Link to match a regex pattern with a url. It does 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))
    
    0 讨论(0)
  • 2020-12-10 15:52

    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

    Sample usage:

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

    If not, you can always create a custom Expected Condition to wait for url to match a desired regular expression.

    0 讨论(0)
  • 2020-12-10 15:57

    This is how I implemented it eventually. Works well for me:

    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)
    
    0 讨论(0)
  • 2020-12-10 16:00

    Here is an example using WebdriverWait with expected_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))
    
    0 讨论(0)
  • 2020-12-10 16:10

    To really know that the URL has changed, you need to know the old one. Using WebDriverWait the implementation in Java would be something like:

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

    I know the question is for Python, but it's probably easy to translate.

    0 讨论(0)
提交回复
热议问题