Yahoo!で指定キーワードで、特定のドメインが検索順位が何位なのか調べる
Pythonでスクレイピングしてみました。以前は、PHPでやっていたんですが、定期的に実施するんだったら、Google App Engineでやってみたらいいんじゃない?と思って、まずはPythonで書いてみました。
今回は、「Yahoo!検索での検索結果で、指定キーワード、特定のドメインが検索結果で何位なのか調べる」のをしてみました(googleとかは、また今度)。
BeautifulSoup
初めて使ってみたんですが、こう、使い方がイマイチわからない...
どうしてだろう?Pythonのコードになれないから?
Yahooへアクセスでのユーザーエージェント
ユーザーエージェントを指定しない場合と、指定する場合でかえってくる結果が異なります。iPhoneとかなら違うだろうなあ、とは思っていたんですが、ユーザーエージェントについては注意しどころかも
opener = urllib2.build_opener()
#opener.addheaders = [('User-agent', 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)')]
オブジェクトの話
PHPで書いていると、文字列の結合は「.」で、何でも結合してしまいます。でも、Pythonだとオブジェクトについて意識をしていないと、結合できない。ここらへんは、慣れが必要ですね
Python本を読んだ方が良さそう
コード
#!/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 = 'はてな' yahoo = 'http://search.yahoo.co.jp/search?ei=UTF-8&n=100&p=' opener = urllib2.build_opener() url = yahoo + keyword html = opener.open(url).read() soup = BeautifulSoup.BeautifulSoup(html) tags = soup.find('ol') i = 1 for tag in tags.findAll('li'): html = tag.find('em') text = '' if html.string: text = html.string else: contents = html.contents text = ''.join([str(content) for content in contents[:]]) text = re.sub("<[^>]*>", "", text) text = text.split('/') if text[0] == domain: print str(i) + '位:' + str(text[0]) i = i + 1
書籍
- 作者: 辻真吾
- 出版社/メーカー: 技術評論社
- 発売日: 2010/04/24
- メディア: 大型本
- 購入: 19人 クリック: 199回
- この商品を含むブログ (33件) を見る
- 作者: Mark Lutz,夏目大
- 出版社/メーカー: オライリージャパン
- 発売日: 2009/02/26
- メディア: 大型本
- 購入: 12人 クリック: 423回
- この商品を含むブログ (124件) を見る