Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform a WebDriverWait() or similar check on a Regular Expression in Python

I would like to be able to perform something similar to a WebDriverWait(), i.e:

WebDriverWait(driver, 60).until(
    expected_conditions.text_to_be_present_in_element((By.XPATH, "//tr[5]/td[11]/div"), "1.000000")
)

...for a regular expression, where it waits for an allotted amount of time before failing. I am aware I could do something, such as...

assert re.search(r"[0,1]{1}.[0-9]{6}", driver.find_element_by_xpath("//tr[5]/td[11]/div").text)

...or I could replace search with match in the above example. The problem with this method is it'll fail if the object.. (1) hasn't loaded yet or.. (2) is still in the process of changing to what's expected. I could do something like...

for x in range (1,60):
    try:
        assert re.search(r"[0,1]{1}.[0-9]{6}", driver.find_element_by_xpath("//tr[5]/td[11]/div").text)
    except AssertionError:
        if x < 60:
            time.sleep(1)
        else:
            raise AssertionError

...where it checks every second for 60 seconds to see if the assert statement has evaluated to true. This could fit into a module or class. What I'm wondering is if there is a more elegant solution, in Python for the Selenium WebDriver, to handling this that I'm unaware of.

like image 319
rwbyrd Avatar asked May 06 '26 18:05

rwbyrd


1 Answers

If you look into what an "Expected Condition" is, you would find it easy to make a custom one:

import re

from selenium.webdriver.support.expected_conditions import _find_element


class text_match(object):
    def __init__(self, locator, regexp):
        self.locator = locator
        self.regexp = regexp

    def __call__(self, driver):
        element_text = _find_element(driver, self.locator).text
        return re.search(self.regexp, element_text)

Usage:

WebDriverWait(driver, 60).until(
    text_match((By.XPATH, "//tr[5]/td[11]/div"), r"[0,1]{1}.[0-9]{6}")
)
like image 113
alecxe Avatar answered May 08 '26 14:05

alecxe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!