Googleで何位なのか調べてくれるPythonのスクリプト
「Yahoo!で指定キーワードで、特定のドメインが検索順位が何位なのか調べる - めも帖」にて、Yahoo!の検索結果について何位なのか、調べてくれるPythonのスクリプトを書きました。今回は、「Googleでの検索結果で、指定キーワード、特定のドメインが検索結果で何位なのか調べる」のをしてみました。
Yahoo!について用意していたので、今回は比較的楽に作れました。それにしても、未だにPythonの気持ちはわからないです。Pythonについて一通り本を読んだりした方がいいんでしょうね(時間効率から考えても)。
ソース
- MacOS X 10.6にてテスト
#!/usr/bin/env python # -*- coding: utf-8 -*- from pprint import pprint from BeautifulSoup import BeautifulSoup,NavigableString import urllib2,sys,re import BeautifulSoup domain = 'd.hatena.ne.jp' keyword = 'はてな' results = [] # 結果 yahoo = 'http://search.yahoo.co.jp/search?ei=UTF-8&n=100&p=' google = 'http://www.google.co.jp/search?hl=ja&num=100&q=' opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)')] url = google + keyword html = opener.open(url).read() soup = BeautifulSoup.BeautifulSoup(html) tags = soup.find('ol') i = 1 for tag in tags.findAll('li'): div = tag.find('div') html = div.find('cite') text = '' if html: contents = html.contents text = ''.join([str(content) for content in contents[:]]) text = re.sub("<[^>]*>", "", text) text = text.split('/') if text[0] == domain: result = {} result[i] = text[0] results.append(result) print str(i) + '位:' + str(text[0]) i = i + 1