簡體   English   中英

等待 - 在使用 Selenium 和 Java 的 Yahoo Finance 頁面中,預期條件不適用於自動建議

[英]Wait- Expected conditions not working for auto-suggestion within Yahoo Finance page using Selenium and Java

如果 webelement 在等待條件內被識別,則下面的代碼無法識別它們的列表。 我收到一個超時異常,無法識別指定 xpath 的元素。

但是,如果我在沒有等待條件的情況下直接訪問元素,則將值分配給列表變量,為什么會這樣?

WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.get("https://www.finance.yahoo.com");
driver.manage().window().maximize();
driver.findElement(By.xpath("//input[@id='yfin-usr-qry']")).sendKeys("nclh");

WebDriverWait wait = new WebDriverWait(driver,5);
List<WebElement>dd_list= wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//ul[@class='modules_list__1zFHY']/li")));
System.out.println(dd_list.size());

for(WebElement ele : dd_list) {

    if (ele.getText().contains("NCLH.VI")) {
        System.out.println("i got the element");
    }
}

為什么會這樣?

您定位的元素永遠不會同時全部可見。 您的 xpath 返回 15 個元素,其中只有 10 個可見。 暗示您的條件永遠不會滿足(因此超時異常)。 只需優化您的 xpath 以定位您感興趣的元素:那些具有可見性的元素,例如"//ul[@class='modules_list__1zFHY']/li[@data-type='quotes']"

在此處輸入圖片說明

雅虎財經網站包含支持ReactJS 的元素。 因此,您需要引入WebDriverWait以使document.readyState complete ,您可以使用以下Locator Strategies

  • 代碼塊:

     driver.get("https://www.finance.yahoo.com"); new WebDriverWait(driver, 120).until(webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete")); WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@id='yfin-usr-qry']"))); element.click(); element.sendKeys("nclh"); System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//ul[@class='modules_list__1zFHY']//li[@data-type='quotes']"))).size())
  • 控制台輸出:

     6
  • 瀏覽器快照:

雅虎財經

暫無
暫無

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

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