Can I find an element using regex with Python and Selenium?

I need to click the dropdown list and click on the hidden element on it. html javascript will be generated and I won’t know the name or class name, but I will know that there will be a phrase in it. Is it possible to find an element by a regular expression, and then click on it with selenium?

+4
source share
2 answers

You can't just do regular expression searches with the built-in locators of selenium selenium web, but you have a few things that can help you:


CSS :

a[href*=desiredSubstring]  # contains
a[href^=desiredSubstring]  # starts-with
a[href$=desiredSubstring]  # ends-with

, , Python, :

import re

pattern = re.compile(r"^Some \w+ text.$")

elements = driver.find_elements_by_css_selector("div.some_class")
for element in elements:
    match = pattern.match(element.text)
    if match:
        print(element.text)
+7

import re . <b></b> , 3 .

import re
from lxml import html, etree

tree = html.fromstring(browser.page_source)
party_table = tree.xpath("//table")
assert len(party_table) == 1

CURRENT_PARTIES = []
for row in party_table[0].xpath("tbody/tr"):
    cells = row.xpath("td")
    if len(cells) != 3:
        continue

    if cells[1].text == "represented by":
        match = re.search(r'<b>(.+?)</b>', etree.tostring(cells[0]), re.IGNORECASE)
        print "MATCH: ", match
0

Source: https://habr.com/ru/post/1620367/


All Articles