我有一个网页,其中有多个容器,每个容器都有一个标题(fooHeading),名称(fooName)和一个按钮(fooButton)。
同一页面上会有多个容器,如下所示:
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ fooTitle fooButton /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
每个容器的html看起来与以下内容相同:
<div class="fooHeading">
<span class="fooName">
fooTitle
</span>
<button class="fooButton"></button>
</div>
FooTitle是唯一可以改变的东西。如何基于fooTitle是什么来唯一地单击fooButton?
答案 0 :(得分:2)
我推荐xpath:
WebElement button = driver.findElement(By.xpath("//span[contains(text(), 'fooTitle')]/../button"));
这会找到包含文字span
的{{1}}。 fooTitle
将升至..
,然后找到div
的孩子button
。
答案 1 :(得分:0)
我的项目中遇到了这样的问题,而在selenium中创建脚本时,所有传统方法都失败了,如 xpath,css selector 等。
如果您遇到同样的情况,那么我的方法可能会对您有所帮助 首先,您必须检查按钮标记的总计数,然后查找按钮计数的位置,例如它的位置是 pos
List<WebElement> element = driver.findElements(By.tagName("button"));
Iterator<WebElement> itr = element.iterator();
int count=0;
WebElement e = null ;
while(itr.hasNext())
{
count++;
e = (WebElement) itr.next();
if(count==pos)
break;
}
//System.out.println(count);
//for checking total count without using break in while loop
e.click();