使用正则表达式与selenium驱动程序标签选择器

huangapple go评论81阅读模式
英文:

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:

&lt;img class=&quot;my-img-12&quot;&gt;

where the latest 2 numbers are always different.
I tried these ways but no one seems to work:

    List&lt;WebElement&gt; allElement = driver.findElements(By.cssSelector(&quot;img[class^=&#39;my-img-\\d{1,}&#39;]&quot;));

or

    List&lt;WebElement&gt; allElement = driver.findElements(By.xpath(&quot;.//img[starts-with(@class, &#39;my-img-&#39;) and  &#39;my-img-&#39; = translate(@class, &#39;0123456789&#39;, &#39;&#39;) and string-length(@class) &gt; 1])&quot;));

the latest option was suggested here: Stack question

if you're thinking about this:

    List&lt;WebElement&gt; allElement = driver.findElements(By.cssSelector(&quot;img[class^=&#39;my-img-&#39;]&quot;));

It's not gonna works because there could be some attributes like this:

&lt;img class=&quot;my-img-wordsOccurrences&quot;&gt;

答案1

得分: 0

可以尝试使用XPath的contains方法:

List<WebElement> allElement = driver.FindElements(By.Xpath(".//<在此处定义根元素>[contains(@class, 'my-img-')]")
英文:

You can try using XPath contains:

List&lt;WebElement&gt; allElement = driver.FindElements(By.Xpath(&quot;.//&lt;define root element here&gt;[contains(@class, &#39;my-img-&#39;)]&quot;)

huangapple
  • 本文由 发表于 2020年10月4日 03:36:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/64188256.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定