BeautifulSoupを使ってGoogleの表示順位を調べる
BeautifulSoupはHTML解析用のライブラリです。htmllib.HTMLParserやHTMLPaprser.HTMLParserと違い、正しくないHTMLも扱えるようです。これを使ってGoogleの表示順位を調べるスクリプトを書いてみました。
#!python # vim:fileencoding=utf-8 import re import sys import time import urllib2 import urlparse from BeautifulSoup import BeautifulSoup g_url = "http://www.google.co.jp/search?hl=ja&num=100&q=" next_text = u"次へ" interval = 3 client_encoding = "cp932" server_encoding = "utf-8" try: keyword, url = sys.argv[1:] except ValueError: sys.exit() print "keyword:", keyword print "url :", url opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] keyword = keyword.decode(client_encoding).encode(server_encoding) search_url = g_url + urllib2.quote(keyword) rank = 0 page = 1 while search_url: print "\rpage : %d" % page, sys.stdout.flush() html = opener.open(search_url).read() soup = BeautifulSoup(html) # HTMLを解析 # Unicode文字列に変換される # キャッシュや関連ページへのリンクを除外したいので # class属性が"l"のAタグだけを取得 for a in soup.findAll("a", {"class":"l"}): rank += 1 href = a["href"] # href属性でURLを取得 # 指定されたURLが見つかれば、結果を表示して終了 if href.startswith(url): # Aタグで囲まれた文字列を取得 title = "".join([c.string for c in a.contents]) print "\nrank :", rank print "href :", href print "title:", title search_url = "" break # 指定したURLが見つからなければ、次の検索結果を調べる else: # 次の検索結果へのリンクを取得 next = soup.find(lambda tag: tag.name=="a" and tag.b and tag.b.string==next_text) if next: search_url = urlparse.urljoin(g_url, next["href"]) page += 1 time.sleep(interval) else: # 次へのリンクが見つからなければ終了 print u"圏外です" search_url = ""
$ python test.py "python インストール" http://www.hlj.com/~tanoue/ keyword: python インストール url : http://www.hlj.com/~tanoue/ page : 2 rank : 158 href : http://www.hlj.com/~tanoue/Python/Mac/mpy00.html title: Mac de Python