如何使用XPath选择特定容器(由CSS类定义的<div>)中的跨度元素?

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

How to select span elements of specific container (<div> defined by CSS class) using Xpath?

问题

Here's the translated code part:

List<WebElement> MainCategory = driver.findElements(By.xpath("//span[@class=\"my_span\"]"));

Please note that I've only provided the translation of the code part you provided, as per your request. If you have any further questions or need additional assistance, feel free to ask.

英文:

i have the following HTML stucture :

  &lt;div class=&quot;divone&quot;&gt;&lt;span class=&quot;my_sapn&quot;&gt;Sports&lt;/span&gt;&lt;/div&gt;
  &lt;div class=&quot;divtwo&quot;&gt;&lt;span class=&quot;my_sapn&quot;&gt;Arts&lt;/span&gt;&lt;/div&gt;
  &lt;div class=&quot;divtwo&quot;&gt;&lt;span class=&quot;my_sapn&quot;&gt;Computer&lt;/span&gt;&lt;/div&gt;
  &lt;div class=&quot;divone&quot;&gt;&lt;span class=&quot;my_sapn&quot;&gt;Fashion&lt;/span&gt;&lt;/div&gt;
  &lt;div class=&quot;divtwo&quot;&gt;&lt;span class=&quot;my_sapn&quot;&gt;Familly&lt;/span&gt;&lt;/div&gt;

What i want to achive is get all elements that have the class my_span inside the divs that have the class divone only. <br>
my code get all span with the class my_span, output : Sports, Arts , Computer , Fashion , Familly
<br> the desired output : Sports , Fashion
<br>Mycode :

List&lt;WebElement&gt; MainCategory = driver.findElements(By.xpath(&quot;//span[@class=\&quot;my_span\&quot;]&quot;));

PS : i must use By.xpath not By.classame

答案1

得分: 3

有一种实现这个结果的方法是使用以下的 XPath-1.0 表达式:

List<WebElement> MainCategory = driver.findElements(By.xpath("//div[@class='divone' and span/@class='my_span']/span"));

另一种实现相同输出的方法是:

List<WebElement> MainCategory = driver.findElements(By.xpath("//span[../@class='divone' and @class='my_span']"));

在两种情况下输出都是相同的:

Sports
Fashion

英文:

One way to achieve this result is using the following XPath-1.0 expression:

List&lt;WebElement&gt; MainCategory = driver.findElements(By.xpath(&quot;//div[@class=&#39;divone&#39; and span/@class=&#39;my_span&#39;]/span&quot;));

Another way to achieve the same output is

List&lt;WebElement&gt; MainCategory = driver.findElements(By.xpath(&quot;//span[../@class=&#39;divone&#39; and @class=&#39;my_span&#39;]&quot;));

The output in both cases is the same:

> Sports
Fashion

huangapple
  • 本文由 发表于 2020年7月26日 03:34:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/63092719.html
匿名

发表评论

匿名网友

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

确定