我需要单击一个下拉列表并单击其中的一个隐藏元素。 html 将由 javascript 生成,我不知道 id 或类名,但我知道其中会有一个短语。我可以通过正则表达式找到和元素,然后用 Selenium 点击它吗?
最佳答案
您不能简单地使用内置的 selenium webdriver 定位器进行基于正则表达式的搜索,但您有多种方法可以帮助您:
contains()
和starts-with()
XPath 函数://div[contains(., "Desired text")] //div[starts-with(., "Desired text")]
-
preceding
,preceding-sibling
,following
和following-sibling
如果您知道需要定位的新生成的元素 block 的相对位置,可能会对您有所帮助
还有 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)
关于javascript - 我可以使用 Python 和 Selenium 的正则表达式找到一个元素吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34315533/