簡體   English   中英

org.openqa.selenium.NoSuchElementException 導航到子 div Selenium Java

[英]org.openqa.selenium.NoSuchElementException when navigating to child div Selenium Java

當前頁面是https://www.nintendo.co.uk/Games/Games-347085.html

我已經使用 driver.findElement 為 div.row-page-container 運行了 Selenium 測試,它工作正常

但是當我嘗試通過進一步進入頁面信息下面的紅線來獲取價格值時,我找不到如何訪問 class,它會記錄:org.openqa.selenium.NoSuchElementException:沒有這樣的元素

如何獲得價格價值,同時盡可能避免 XPath?

不知道為什么你不想擁有 XPath。

但是,如果您正在尋找基於游戲名稱的 XPath,那可以得到它的價格。 您可以使用下面的 XPath

//p[text()='Animal Crossing: New Horizons']//following-sibling::p[@class='price-small']//span[@data-price]

或下面的 CSS 也應該足夠了

a[href*='Animal-Crossing-New-Horizons'] > p.price-small > span:nth-child(2)

它基於href Animal-Crossing-New-Horizons

首先使用正確的 xpath 是去除 NoSuchElementException 的重要步驟。用於識別元素的 xpath 是

//p[text()='Animal Crossing: New Horizons']//following-sibling::p[@class='price-small']//span[@data-price]

即使這不能識別,網頁也可能存在一些時間問題,即頁面仍在呈現,並且您已經完成了元素搜索並且沒有獲得元素異常。

您可以使用FluentWait來克服這個問題。

假設您有一個元素,有時只需 1 秒即可出現,有時需要幾分鍾才能出現。 在這種情況下,最好使用FluentWait定義顯式等待,因為這將一次又一次地嘗試查找元素,直到找到它或直到最終計時器用完。

可以定義FluentWait的實例來配置等待條件的最長時間以及必須檢查條件的頻率。用戶還可以配置等待以在等待元素時忽略特定類型的異常,比如頁面上的 NoSuchElementExceptions。

 // Waiting 30 seconds for an element to be present on the page, checking 
// for its presence once every 5 seconds. 
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver) 
                                           .withTimeout(30, SECONDS);
                                           .pollingEvery(5, SECONDS) ;
                                           .ignoring(NoSuchElementException.class);
    

添加顯式等待也可以解決問題:

import org.openqa.selenium.WebElement; 
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
 . . . 
WebDriverWait wait = new WebDriverWait(driver, 10); 
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("element_xpath"))); element.click();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM