我可以在Python和Selenium中使用正则表达式找到一个元素吗? [英] Can I find an element using regex with Python and Selenium?

查看:1154
本文介绍了我可以在Python和Selenium中使用正则表达式找到一个元素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要点击下拉列表并点击其中的隐藏元素。 HTML将由javascript生成,我不会知道id或类的名称,但我会知道它会在其中包含一个短语。我可以找到和元素的正则表达式,然后点击它与硒?

解决方案

你不能简单地做基于正则表达式的搜索,在selenium webdriver定位器中,但是您有多种可能对您有帮助的事情:






还有 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:


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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆