[英]Selenium check if attribute contains part of a string in java
So I have a webpage where the Id's of certain elements are generated dynamically with certain parts changing and certain parts being constant like so: 所以我有一个网页,其中某些元素的ID是动态生成的,其中某些部分发生了变化,某些部分是不变的,如下所示:
<div id= "xxxdiv" title= 'this title'>
<p id = "xxxp">
<table id = "xxxtable" title = 'not derp'>
<div id = "yyyydiv">
<table id = "yyytable" title= 'derp'>
<table id = "yyytable2" title = 'not derp'>
<table id = "zzztable" title = derp>
I'm trying to do some dynamic lookups on the page that can look for a given element where the id contains a known value. 我正在尝试在页面上进行一些动态查找,以查找ID包含已知值的给定元素。 For instance, I do not always know how many nested elements might exist so the number that gets generated on the end can vary. 例如,我并不总是知道可能存在多少个嵌套元素,因此最终生成的数量可能会有所不同。 So I would like to find an element by xpath where the @title = not derp and the @id contains yyy. 所以我想通过xpath查找一个元素,其中@title = not derp并且@id包含yyy。 How can I accomplish this? 我该怎么做?
driver.findElement(By.xpath("//table[@title='not derp' and contains(@id, 'yyy')]"));
会找到与您的搜索条件相匹配的第一个元素,这将是HTML代码段的<table id = "yyytable2" title = 'not derp'>
。
There are a whole host of relational and logical operators you can use. 您可以使用大量的关系和逻辑运算符。 In this case, assuming you're looking for the table element, you can use: //table[@title='not derp' and contains(@id,'yyyy')]
在这种情况下,假设您要查找表格元素,则可以使用: //table[@title='not derp' and contains(@id,'yyyy')]
I would like to find an element by xpath where the @title = not derp and the @id contains yyy 我想通过xpath找到一个@title = not derp且@id包含yyy的元素
I would suggest you cssSelector
instead, because using By.cssSelector()
to locate an element is much faster than By.xpath()
in performance. 我建议您改为使用cssSelector
,因为在性能上使用By.cssSelector()
定位元素比By.xpath()
快得多。 So you should try as below :- 所以你应该尝试如下:
driver.findElement(By.cssSelector("table[id *= 'yyy'][title = 'not derp']"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.