【问题标题】:Selenium Webdriver : not displaying the correct Li elementsSelenium Webdriver:不显示正确的 Li 元素
【发布时间】:2017-04-06 21:14:27
【问题描述】:

在下面的代码中,我希望看到大小为 18,但它显示为 0。我无法弄清楚原因。

我要去Amazon 搜索书籍,并最终希望将书名存储在一个数组中。谢谢!

@Test
public void searchTestOne(){
    System.setProperty("webdriver.gecko.driver", "C:\\geckodriver\\geckodriver.exe");
    WebDriver driver = new FirefoxDriver();
    driver.get("http://www.amazon.in");
    driver.manage().window().maximize();        

    driver.findElement(By.id("twotabsearchtextbox")).sendKeys("Books");
    driver.findElement(By.className("nav-input")).click();

    List<WebElement> result = driver.findElements(By.xpath(".//*[@id='atfResults']/ul[@id='s-results-list-atf']/li"));

    System.out.println(result.size());

【问题讨论】:

    标签: java selenium selenium-webdriver


    【解决方案1】:

    页面是动态的,这意味着一旦 selenium 认为页面已加载,内容实际上还没有出现在页面上。所以你必须先等待结果。

    在这种情况下,您可以等到您期望多个结果,因为列表应该一次全部加载:

    WebDriverWait wait = new WebDriverWait(driver, timeoutInSeconds);
    //Note this isn't giving you the titles, it's giving you the entire list item
    By bookSearchResults = By.xpath(".//*[@id='atfResults']/ul[@id='s-results-list-atf']/li");
    
    wait.until(ExpectedConditions.numberOfElementsToBeMoreThan(bookSearchResults, 1));
    
    //Then continue on as you were
    List<WebElement> result = driver.findElements(bookSearchResults);
    ....
    

    您也可以尝试等待结果 div。

    【讨论】:

    • 我注意到等待条件不会等到所有元素都被加载,因为条件是搜索结果 = 1。我将等待更改为 5 秒,然后加载所有元素。只是想告诉..
    • @vijaya 很有趣。我原以为所有结果都会同时加载,很好 :) 需要注意的一点是,您设置的超时不一定要等待那么长时间,但它会等待您设置的条件的时间,在这种情况下为ExpectedConditions.numberOfElementsTo...。如果您想等待更多元素加载,您可以将其作为numberOfElementsToBeMoreThan(elementsBy, amountOfElements) 中的第二个参数。如果您觉得这是一个正确的答案,请随时投票和/或用复选标记将其标记为正确答案。干杯!
    猜你喜欢
    • 2014-11-03
    • 2019-11-03
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多