BeautifulSoupとGoogleで遊んでみた


Google使
#!/usr/bin/env python
# coding: UTF-8
import urllib, urllib2, sys
from BeautifulSoup import BeautifulSoup


OPENER = urllib2.build_opener()
OPENER.addheaders = [("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)")]
# hl=en⇒英語, num=1⇒表示する検索結果は1件, q=⇒サーチクエリ
BASE_URL = "http://www.google.co.jp/search?hl=en&num=1&q="

def get_num_of_results( que ) :
    u"""
    Googleでの検索結果数をintで返すメソッド
    """
    # イディオムで調べたりするのを考慮してクオーテーションで囲ってからURLエンコード
    url = BASE_URL +  urllib.quote( "\"%s\"" % que )
    html = OPENER.open( url ).read()
    # 念のため
    html = html.decode( "utf-8", "ignore" ).encode("utf-8") 
    soup = BeautifulSoup( html )
    
    # 検索結果数に該当する部分をスクレイピング。
    num_str = soup.findAll("p")[1].findAll("b")[2].string
    
    # 3ケタ区切りのカンマを削る
    num_str = "".join( [ str for str in num_str.split(",") ])

    return int( num_str )

def print_searchterm_and_num( search_term ) :
    num = get_num_of_results( search_term )
    print "'%s' => %s" % ( search_term, num )

def main() :
    if len( sys.argv ) == 1 :
        print u"検索語を指定して下さい"
        sys.exit(1)
    else :
        for search_term in sys.argv[1:] :
            print_searchterm_and_num( search_term )

if __name__=="__main__":
    main()
    sys.exit(0)

lxmlBeautifulSoup使




Results 1 - 10 of about 214,000,000 for abc

 214,000,000 

使

 "test.py"


使()

$ python test.py "bored of" "bored with" "bored by"
'bored of' => 2530000
'bored with' => 3480000
'bored by' => 791000




$ python test.py 南明菜 南明奈
'南明菜' => 45500
'南明奈' => 1510000




$ python test.py FreeBSD NetBSD OpenBSD
'FreeBSD' => 26200000
'NetBSD' => 7900000
'OpenBSD' => 5890000

GoogleAPI使