我想在搜索後輸入一些字符串後,從google獲得搜索結果。我如何使用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"));
}
我該如何解決這個問題?
我應該在哪裏放這段代碼? –
@PeterPenzov提交後和搜索鏈接之前。 – alecxe
順便問一下,你知道爲什麼第二個結果列表不起作用嗎?我也想修復它。 –