[英]Selenium Xpath Not Matching Items
我正在嘗試使用Selenium的Xpath功能來查找一組元素。 我已經在FireFox上使用FirePath來創建和測試我提出的Xpath,並且效果很好,但是當我在Selenium的c#測試中使用Xpath時,沒有任何返回。
var MiElements = this._driver.FindElements(By.XPath("//div[@class='context-menu-item' and descendant::div[text()='Action Selected Jobs']]"));
HTML看起來像這樣: 任何人都可以指出我的意思,因為我閱讀過網絡上的所有內容都對我說這個Xpath是正確的。
謝謝大家提前。
請發布實際的 HTML,以便我們可以簡單地將其“放入” HTML文件中並自己嘗試,但我注意到類名的末尾有一個空格:
<div title="Actions Selected Jobs." class="context-menu-item " .....
因此,強制XPath首先去除尾隨空格:
var MiElements = this._driver.FindElements(By.XPath("//div[normalize-space(@class)='context-menu-item' and descendant::div[text()='Action Selected Jobs']]"));
也許您沒有考慮元素需要加載的時間,而是在尚無法“搜索”它們時尋找它們。 更新我跳過了有關此問題的示例。 請參閱Slanec的評論。
無論如何,Selenium建議盡可能避免使用xpath進行搜索,因為它更慢且更“脆弱”。 您可以找到這樣的元素:
//see the method code below
WebElement div = findDivByTitle("Action Selected Jobs");
//example of searching for one (first found) element
if (div != null) {
WebElement myElement = div.findElement(By.className("context-menu-item"));
}
......
//example of searching for all the elements
if (div != null) {
WebElement myElement = div.findElements(By.className("context-menu-item-inner"));
}
//try to wrap the code above in convenient method/s with expressive names
//and separate it from test code
......
WebElement findDivByTitle(final String divTitle) {
List<WebElement> foundDivs = this._driver.findElements(By.tagName("div"));
for (WebElement div : foundDivs) {
if (element.getAttribute("title").equals(divTitle)) {
return element;
}
}
return null;
}
這是大概的代碼(根據您的解釋),您應該使其更適合您的目的。 同樣,請記住要考慮加載時間,並將實用程序代碼與測試代碼分開。
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.