我在嘗試使用 selenium 和 java 識別元素時遇到問題...對于以下鏈接:
<a id="newSearchNavigateHeadingEventId_0" class="search-heading" ng-href="book/event?eid=757231&" target="_self" href="book/event?eid=757231&">
<h2 ng-bind="event.EventDisplayName" class="ng-binding">Makerspace Docklands - Safety Induction</h2>
</a>
我嘗試了以下...
WebElement we = myDriver. findElement(By.linkText("Makerspace Docklands - Safety Induction"));
WebElement we = myDriver.findElement(By.id("newSearchNavigateHeadingEventId_0"));
WebElement we = myDriver.findElement(By.xpath( " //a[@id='newSearchNavigateHeadingEventId_01'] "));
WebElement we = myDriver.findElement(By.xpath("//a[text()='Makerspace Docklands - Safety Induction']"));
WebElement we = myDriver.findElement(By.xpath("//a[@href='book/event?eid=757231&']")) ;
但我不斷收到以下訊息...
org.openqa.selenium.NoSuchElementException: Unable to locate element: ....
有人可以建議什么是正確的路徑,以便我可以單擊以下鏈接:
we.click();
uj5u.com熱心網友回復:
要將帶有文本的元素標識為Makerspace Docklands - Safety Induction,您可以使用以下任一定位器策略:
css選擇器:
WebElement we = driver.findElement(By.cssSelector("a.search-heading[id^='newSearchNavigateHeadingEventId']>h2.ng-binding[ng-bind*=EventDisplayName]"));路徑:
WebElement we = driver.findElement(By.xpath("//a[@class='search-heading' and starts-with(@id, 'newSearchNavigateHeadingEventId')]/h2[contains(., 'Makerspace Docklands') and contains(@ng-bind, 'EventDisplayName')]"));
然而,由于該元素是一個動態的元素,以便于確定需要引起元素WebDriverWait的visibilityOfElementLocated(),你可以使用以下的定位策略:
css選擇器:
WebElement we = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("a.search-heading[id^='newSearchNavigateHeadingEventId']>h2.ng-binding[ng-bind*=EventDisplayName]")));路徑:
WebElement we = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[@class='search-heading' and starts-with(@id, 'newSearchNavigateHeadingEventId')]/h2[contains(., 'Makerspace Docklands - Safety Induction') and contains(@ng-bind, 'EventDisplayName')]")));
參考
您可以在以下位置找到有關NoSuchElementException的詳細討論:
- NoSuchElementException,Selenium 無法定位元素
uj5u.com熱心網友回復:
謝謝...我發現這也對我有用...
WebElement we = myDriver.findElement (By.xpath ("//*[contains(text(),'Makerspace Docklands - Safety Induction')]"));
we.click();
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/342828.html
