我想在输入一些字符串进行搜索后从谷歌获取搜索结果。我怎么能用Selenium做到这一点?到目前为止,我设法创建了这个:
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com/xhtml");
Thread.sleep(5000);
WebElement searchBox = driver.findElement(By.name("q"));
searchBox.sendKeys("ChromeDriver");
searchBox.submit();
System.out.println("Current Url: " + driver.getCurrentUrl());
List<WebElement> results = driver.findElements(By.xpath("//h3[@class=r]/a"));
for(int i=0; i<results.size(); i++){
System.out.println(">>>>> results " + results.get(i).getText());
}
// second attempt
List<WebElement> allSearchResults = driver.findElements(By.cssSelector("ol li h3>a"));
//iterate the above list to get all the search titles & links from that page
for (WebElement eachResult : allSearchResults)
{
System.out.println("Title : " + eachResult.getText() + ", Link : " + eachResult.getAttribute("href"));
}
我如何解决这个问题?
答案 0 :(得分:1)
提交搜索表单后,您需要wait for the results to appear:
WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("h3.r a")));
答案 1 :(得分:0)
你走在正确的轨道上。您的xpath似乎不正确。你错过了r
旁边的单引号List<WebElement> results = driver.findElements(By.xpath("//h3[@class=r]/a"));
应该是
List<WebElement> results = driver.findElements(By.xpath("//h3[@class='r']/a"));