2016-06-27 3 views
1

검색 문자열을 입력 한 후 google에서 검색 결과를 가져오고 싶습니다. 셀레늄으로 어떻게 할 수 있습니까? 지금까지 나는 이것을 만들 수 있었다 :Google 검색 페이지에서 전체 검색 결과 가져 오기

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

이어야한다 R 옆에 작은 따옴표가 누락되었습니다 :

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

이 코드를 어디에 넣어야합니까? –

+0

@ PeterPenzov 링크를 제출하기 전에 제출해야합니다. – alecxe

+0

그런데 두 번째 결과 목록이 작동하지 않는 이유는 무엇입니까? 나는 그것을 고치고 싶다. –

0

오른쪽 트랙에 있습니다. 귀하의 xpath가 틀린 것으로 보입니다. 당신은

List<WebElement> results = driver.findElements(By.xpath("//h3[@class=r]/a")); 

검색 양식 제출 후에는 wait for the results to appear 필요

List<WebElement> results = driver.findElements(By.xpath("//h3[@class='r']/a")); 

screenshot of google search

+0

감사합니다, 그러나 다시 I 빈 결과를 얻으십시오. 왜 그런가? –