2016-02-02 24 views
0

我正在嘗試從谷歌搜索頁中提取(前5個)網址。我試圖使用硒web驅動程序提取它。我打開Firefox並加載頁面,但正則表達式與網頁上的網址不匹配。我如何獲取網址?從谷歌搜索頁中提取網址

到目前爲止,我已經用下面的代碼:

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
import org.openqa.selenium.WebDriver; 
import org.openga.selenium.firefox.FirefoxDriver; 

public class Weburlext { 

public static void main (String[] args){ 

String line = null; 
Webdriver driver = new FirefoxDriver(); 
driver.ger("http://www.google.co.in/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=sample%20data"); 

String regex="@^(http\\:\\/\\/|https\\:\\/\\/)?([a-z0-9][a-z0-9\\-]*\\.)+[a-z0-9][a-z0-9\\-]*[email protected]"; 
Pattern p = Pattern.compile(regex,pattern.CASE_INSENSITIVE | Pattern.DOTALL); 
Matcher m = p.matcher(line); 

System.out.print(line); 

driver.quit(); 

} 
} 
+1

[別這樣做](http://stackoverflow.com/questions/22657548/is-it-ok-to-scrape-data-from-google-results),你冒着被IP阻擋的風險。使用Google API自動訪問Google搜索結果。 – Amadan

+0

在您提供的代碼行中始終爲空。 – Ardesco

+0

你必須先檢查你的正則表達式。 http://www.regexpal.com/ – Sagar007

回答

0

我很好奇,爲什麼你正在使用正則表達式來在PageSource的HTTP模式相匹配。使用Selenium查找前5個結果的正確方法是找到結果元素,然後獲取屬性「href」。請參見下面的代碼:

driver.get("https://www.google.com.ph/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=sample%20data"); 

List<WebElement> results = driver.findElements(By.cssSelector("div[class='rc'] > h3 > a")); 
results.forEach(e -> System.out.println(e.getAttribute("href")));