如何从具有相同类名的 div 元素中进行选择(Selenium)

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

How to choose an element from divs having the same classnames (Selenium)

问题

我对Selenium还很陌生,所以我卡住了。

这里有一张截图显示检查元素,两个div几乎是相同的,但它们内部都有另一个包含不同文本值的div:图片

我能否通过检查getText()是否等于...来选择我想要的div呢?我找到了以下方法,但据我所知,我永远不会知道流的顺序:

new ArrayList<>(
    chromeDriver.findElements(By.xpath("//div[@class='sign-up-row']"))
).get(1).click();

谢谢大家。

英文:

I am new to Selenium which is probably why I am stuck.

Here is the screenshot showing inspect where two divs are almost identical but they both have another div inside containing different text values: Image.

Could I somehow choose the div I want by checking if getText() is equal to ...?
I found the following way but as far as I know, I would never know the order of the stream:

 new ArrayList&lt;&gt;(chromeDriver.findElements(By.xpath(&quot;//div[@class=&#39;sign-up-row&#39;]&quot;))).get(1).click();

Thank you guys.

答案1

得分: 0

你可以使用在 div 标签内的标签中出现的文本来创建一个 xpath。这将返回你所感兴趣的特定元素。以下是 xpath 的示例:

//div/div[text()='textforcomparison']
英文:

You can create an xpath using the text present in the tag within the div tag. This would return the specific element you are interested in.
Example for the xpath:

//div/div[text()=&#39;textforcomparison&#39;]

答案2

得分: 0

你可以按照以下方法进行操作。

    List<WebElement> lst = driver.findElements(By.xpath("//div[@class='sign-up-row']"));
	for (int i = 0; i < lst.size(); i++) {
		if(lst.get(i).getText().equals("要比较的文本")) {
			lst.get(i).click();
			//如果在匹配后要终止循环
			break;
		}
	}
英文:

You can follow below approach.

    List&lt;WebElement&gt; lst = driver.findElements(By.xpath(&quot;//div[@class=&#39;sign-up-row&#39;]&quot;));
	for (int i = 0; i &lt; lst.size(); i++) {
		if(lst.get(i).getText().equals(&quot;Text to Be Compared&quot;)) {
			lst.get(i).click();
			//If you want to break the foe loop after the match 
			break;
		}
	}

答案3

得分: 0

使用Xpath如下所示:

示例:对于//div[@class=&#39;sign-up-row&#39;]这个节点

使用 text()

//div[@class=&#39;sign-up-row&#39; and .//span[text()=&#39;Remember me.&#39;)]]

或者使用 contains

//span[contains(text(), &#39;Remember&#39;)]/ancestor::div[@class=&#39;sign-up-row&#39;]

使用点 . 可以找到内部元素:

//div[@class=&#39;sign-up-row&#39; and contains(., &#39;Remember&#39;)]
英文:

Using Xpath like below:

example for //div[@class=&#39;sign-up-row&#39;] this node

use text():

//div[@class=&#39;sign-up-row&#39; and .//span[text()=&#39;Remember me.&#39;)]]

Or use with contains:

//span[contains(text(), &#39;Remember&#39;)]/ancestor::div[@class=&#39;sign-up-row&#39;]

Use the dot . can find inner element:

//div[@class=&#39;sign-up-row&#39; and contains(., &#39;Remember&#39;)]

huangapple
  • 本文由 发表于 2020年9月16日 15:20:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/63915021.html
匿名

发表评论

匿名网友

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

确定