英文:
Use Regex with selenium driver tag selectors
问题
我正在尝试配置一个正则表达式来查找具有以下属性的所有元素。HTML 标签类似于:
<img class="my-img-12">
其中最后的2个数字始终不同。我尝试了以下几种方法,但似乎都不起作用:
List<WebElement> allElement = driver.findElements(By.cssSelector("img[class^='my-img-\\d{1,}']"));
或者
List<WebElement> allElement = driver.findElements(By.xpath(".//img[starts-with(@class, 'my-img-') and 'my-img-' = translate(@class, '0123456789', '') and string-length(@class) > 1])"));
最后的选项是在这里提出的:Stack question
如果您考虑过以下内容:
List<WebElement> allElement = driver.findElements(By.cssSelector("img[class^='my-img-']"));
它是不起作用的,因为可能会有一些类似于这样的属性:
<img class="my-img-wordsOccurrences">
英文:
I'm trying to configure a regex to find all elements with such attributes.
The HTML tag is something like:
<img class="my-img-12">
where the latest 2 numbers are always different.
I tried these ways but no one seems to work:
List<WebElement> allElement = driver.findElements(By.cssSelector("img[class^='my-img-\\d{1,}']"));
or
List<WebElement> allElement = driver.findElements(By.xpath(".//img[starts-with(@class, 'my-img-') and 'my-img-' = translate(@class, '0123456789', '') and string-length(@class) > 1])"));
the latest option was suggested here: Stack question
if you're thinking about this:
List<WebElement> allElement = driver.findElements(By.cssSelector("img[class^='my-img-']"));
It's not gonna works because there could be some attributes like this:
<img class="my-img-wordsOccurrences">
答案1
得分: 0
可以尝试使用XPath的contains方法:
List<WebElement> allElement = driver.FindElements(By.Xpath(".//<在此处定义根元素>[contains(@class, 'my-img-')]")
英文:
You can try using XPath contains:
List<WebElement> allElement = driver.FindElements(By.Xpath(".//<define root element here>[contains(@class, 'my-img-')]")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论