2010-12-06 228 views
3

我想定期檢查Google列出了哪些子域。提取Google搜索結果

要獲取子域列表,我在Google搜索框中鍵入'site:example.com' - 它列出了所有子域名結果(我們域名超過20頁)。

什麼是最好的方式來提取只有由'網站:example.com'搜索返回的地址的網址?

我正在考慮編寫一個小的python腳本,它將執行上述搜索並從搜索結果中對URL進行正則表達式(在所有結果頁面上重複)。這是一個好的開始?有沒有更好的方法?

乾杯。

回答

14

正則表達式是用於解析HTML一個壞主意。它閱讀起來很神祕,依賴於格式良好的HTML。

嘗試使用Python的BeautifulSoup。以下是一個示例腳本,用於返回網站前10個網頁的網址:domain.com Google查詢。

import sys # Used to add the BeautifulSoup folder the import path 
import urllib2 # Used to read the html document 

if __name__ == "__main__": 
    ### Import Beautiful Soup 
    ### Here, I have the BeautifulSoup folder in the level of this Python script 
    ### So I need to tell Python where to look. 
    sys.path.append("./BeautifulSoup") 
    from BeautifulSoup import BeautifulSoup 

    ### Create opener with Google-friendly user agent 
    opener = urllib2.build_opener() 
    opener.addheaders = [('User-agent', 'Mozilla/5.0')] 

    ### Open page & generate soup 
    ### the "start" variable will be used to iterate through 10 pages. 
    for start in range(0,10): 
     url = "http://www.google.com/search?q=site:stackoverflow.com&start=" + str(start*10) 
     page = opener.open(url) 
     soup = BeautifulSoup(page) 

     ### Parse and find 
     ### Looks like google contains URLs in <cite> tags. 
     ### So for each cite tag on each page (10), print its contents (url) 
     for cite in soup.findAll('cite'): 
      print cite.text 

輸出:

stackoverflow.com/ 
stackoverflow.com/questions 
stackoverflow.com/unanswered 
stackoverflow.com/users 
meta.stackoverflow.com/ 
blog.stackoverflow.com/ 
chat.meta.stackoverflow.com/ 
... 

當然,你可以每個結果追加到一個列表,以便您可以分析它的子域。我剛剛進入Python並且在幾天前進行了修改,但是這會讓你開始。

3

Google Custom Search API可以提供在ATOM XML格式的結果

Getting Started with Google Custom Search

+0

或採用JSON格式,這非常容易在Python中使用(使用`json`模塊) – 2010-12-07 00:06:47

+4

AFAIK自定義搜索不允許搜索整個網絡,只是選擇的域。搜索的重點可能是瀏覽所有網頁:) – 2011-08-17 16:05:09