小编典典

我可以在python和Selenium中使用正则表达式找到元素吗?

selenium

我需要单击一个下拉列表,然后单击其中的隐藏元素。html将由javascript生成,但我不知道ID或类名,但我知道它将包含一个短语。我可以通过正则表达式查找和元素,然后用selenium单击它吗?


阅读 990

收藏
2020-06-26

共1个答案

小编典典

您不能简单地使用内置的Selenium Webdriver定位器进行基于正则表达式的搜索,但是您可以通过多种操作来帮助您:

        //div[contains(., "Desired text")]
    //div[starts-with(., "Desired text")]

还有 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)
2020-06-26