如何使用java访问selenium中具有相同类名的第二个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23828893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access the second element that has the same class name in selenium using java
提问by Nagarjuna Reddy
When trying to automate our application, there are two buttons with same name.
在尝试自动化我们的应用程序时,有两个同名的按钮。
I'm not able to find a way to recognize these. Please let me know what could be the other ways to identify these elements in selenium webdriver in java
我无法找到识别这些的方法。请让我知道在 java 中的 selenium webdriver 中识别这些元素的其他方法是什么
采纳答案by Santoshsarma
You can use xpath indexing option.
您可以使用 xpath 索引选项。
By.xpath("(//input[@name='Button'])[2]")
回答by Priyanshu Shekhar
You can go with xpath always if there is no uniqueness with attribute. For e.g. if you want to find an element which has text foo
and name button
then I'll prefer xpath as below if name is not unique there:
如果属性没有唯一性,您可以始终使用 xpath。例如,如果您想找到一个具有文本foo
和名称的元素,button
那么如果名称在那里不是唯一的,我会更喜欢 xpath 如下:
//*[@name='button' and text()='foo']
Or For different class but same name
或对于不同的班级但名称相同
//button[@name='button' and @class='xyz']
or For different text but same name
或对于不同的文本但相同的名称
//input[@name='button' and contains(text(),'Click Here')]
or for different tags but same name
或用于不同的标签但名称相同
//button[@name='button']
//input[@name='button']
Just go with any unique property and make a customized xpath.
只需使用任何独特的属性并制作自定义的 xpath。
I hope you can also use java script for this as well for e.g.
我希望您也可以为此使用 java 脚本,例如
WebElement butttonToClick = driver.findElement(By.name("button"));
((JavascriptExecutor)driver).executeScript("arguments[1].click();",butttonToClick );
Where arguments[1]
means second element which has same name.
其中arguments[1]
表示具有相同名称的第二个元素。
回答by Deepika G
You can go with xpath methods like following-sibling/preceding siblings.
您可以使用 xpath 方法,例如跟随兄弟姐妹/前兄弟姐妹。
For example if the Button is located to any unique webelement try to identify that webelement first and by using different xpath methods like following-siblings, content, preceding siblings you can access the web element.
例如,如果 Button 位于任何唯一的 webelement,请尝试首先识别该 webelement,然后通过使用不同的 xpath 方法(例如以下兄弟姐妹、内容、前兄弟姐妹),您可以访问该 web 元素。