Selenium Webdriver:未显示正确的Li元素 [英] Selenium Webdriver : not displaying the correct Li elements
问题描述
在下面的代码中,我希望看到的大小为18,但显示为0.我无法弄清楚为什么.
In the code below , I am expecting to see the size as 18 but it displays 0. I have not been able to figure out why.
我要去 Amazon 搜索书籍,最终希望将书籍标题存储在一个数组中.谢谢!
I am going to Amazon searching for books and ultimately want to store the book titles in a array. Thanks !
@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());
推荐答案
页面是动态的,这意味着一旦selenium认为页面已加载,内容实际上就不在页面上了.因此,您必须首先等待结果.
The page is dynamic, meaning once selenium thinks the page is loaded, the content isn't actually on the page yet. So you have to wait for the results first.
在这种情况下,您可以等到期望得到一个以上的结果,因为列表应该一次全部加载:
In this case, You can wait until you expect more than one result since the list should all load at once:
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.
You could also just try waiting for the results div instead.
这篇关于Selenium Webdriver:未显示正确的Li元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!