我可以在Python和Selenium中使用正则表达式找到一个元素吗? [英] Can I find an element using regex with Python and Selenium?
问题描述
我需要点击下拉列表并点击其中的隐藏元素。 HTML将由javascript生成,我不会知道id或类的名称,但我会知道它会在其中包含一个短语。我可以找到和元素的正则表达式,然后点击它与硒?
你不能简单地做基于正则表达式的搜索,在selenium webdriver定位器中,但是您有多种可能对您有帮助的事情:
contains()
和 starts-with()$ c
$ b
// div [contains(。,Desired text)]
// div [starts-with(。,Desired text)]
在
之前, 在兄弟姐妹之前
, 关注
和 following-sibling
坐标轴,如果您知道新生成的要查找的元素块的相对位置,可能会对您有所帮助
还有 CSS选择器用于元素属性的部分匹配:
<$ p $
a [href * = desiredSubstring]#包含
a [href ^ = desiredSubstring]#开始 -
a [href $ = desiredSubstring]#结束 -
你总是可以找到比需要更多的元素, Python,例如:
import re
pattern = re.compile(r^ Some \ w + text。$
elements = driver.find_elements_by_css_selector(div.some_class)
for eleme nt in元素:
match = pattern.match(element.text)
如果匹配:
print(element.text)
I need to click a dropdown list and click a hidden element with in it. the html will be generated by javascript and I won't know the id or class name but I will know it will have a phrase in it. Can I find and element by regex and then click it with selenium?
You cannot simply do regex-based search with built-in selenium webdriver locators, but you have multiple things that might help you:
contains()
andstarts-with()
XPath functions://div[contains(., "Desired text")] //div[starts-with(., "Desired text")]
preceding
,preceding-sibling
,following
andfollowing-sibling
axis that might help you if you know the relative position of an newly generated block of elements you need to locate
There are also CSS selectors for partial match on element attributes:
a[href*=desiredSubstring] # contains
a[href^=desiredSubstring] # starts-with
a[href$=desiredSubstring] # ends-with
And you can always find more elements than needed and filter them out later in Python, example:
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)
这篇关于我可以在Python和Selenium中使用正则表达式找到一个元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!