您不能简单地使用内置的Selenium Webdriver定位器进行基于正则表达式的搜索,但是您可以通过多种操作来帮助您:
contains()
和starts-with()
XPath函数:
//div[contains(., "Desired text")] //div[starts-with(., "Desired text")]
preceding
,preceding-sibling
,following
和following-sibling
轴线,可以帮助你,如果你知道元素的新生成块的相对位置,你需要找到
还有 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)


