2016-06-27 202 views
1

我想在搜索後輸入一些字符串後,從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")); 
     } 

我該如何解決這個問題?

回答

1

您需要wait for the results to appear

WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds); 
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("h3.r a"))); 
+0

我應該在哪裏放這段代碼? –

+0

@PeterPenzov提交後和搜索鏈接之前。 – alecxe

+0

順便問一下,你知道爲什麼第二個結果列表不起作用嗎?我也想修復它。 –

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")); 

screenshot of google search

+0

謝謝,但我再次得到空的結果。任何想法爲什麼? –