2015-09-28 49 views
2

我试图找到并单击我的页面上的一个元素,但无法使用by.id方法,因为生成了id并且每个会话都发生更改。对于大多数元素,我可以通过使用xpath来解决这个问题,但是有一个下拉菜单,在这里不起作用。我可以点击包含下拉列表的元素,并向我显示选项。如果我找到我需要的元素并复制它的xpath,测试用例将不会起作用,说明它找不到xpath。现在旁边的id我试图点击的元素也有一个类。问题是这个类不是唯一的,下拉菜单中的所有菜单项都有不同的文本。我想要做的是一样的东西:findElement by class where content equals text

driver.findeElement(By.class("x-menu-item-text").equals("Unique text 1here").click() 

类“X-菜单项文本”是不是唯一的,但在这个特殊类的文字。我无法使用该ID,因为这是自动生成的。我想单击的项目或元素的完整代码是:

<a id="ext-comp-1035" class="x-menu-item" hidefocus="true" unselectable="on" href="#"><span id="ext-gen250" class="x-menu-item-text">Unique text 1 here</span></a> 
<a id="ext-comp-1035" class="x-menu-item" hidefocus="true" unselectable="on" href="#"><span id="ext-gen250" class="x-menu-item-text">Unique text 2 here</span></a> 

我在Eclipse(Java)中使用Selenium Webdriver。

Allthough提供的答案似乎在大多数网页和地点工作,还有一种情况,但是,我不能得到它的工作。任何人都可以建议吗? 有一个包含按钮的页面,我想单击其中一个按钮。如果我用下面的语句:

driver.findElement(By.xpath("//*[@class=' x-btn-text' and text()='Add']")).click(); 

我得到一个错误信息

org.openqa.selenium.ElementNotVisibleException: Element is not currently visible and so may not be interacted with 

如果我看我看到源:

<button class=" x-btn-text" id="ext-gen539" type="button">Add</button> 

所以元素存在,且可见。 我试着加入点击语句前wait.until声明,但这并不工作之一:

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@class=' x-btn-text' and text()='Toevoegen']"))); 
driver.findElement(By.xpath("//*[@class=' x-btn-text' and text()='Toevoegen']")).click(); 

的额外信息:可能这个问题是因为我在寻找的是坐落在一个元素弹出窗口?

回答

1

您可以使用XPath定位 https://newcircle.com/bookshelf/selenium_tutorial/locators

By.xpath( “//跨度[@类= 'X-菜单项文本' 和文本()= '独特的文本1此处']”)

+0

谢谢,这个作品! – Hugo

+0

我已经更新了我的问题,因为我有麻烦做同样的另一种元素,不能弄清楚为什么它不工作在那里找到的对象的 – Hugo

+0

查身份证,它是正确的对象? (貌似你发现了另一个,重复的元素) findElement(By.xpath())的getAttribute(“ID”) – Vovka