久しぶりのブログ更新となってしまいました。
ぼちぼちやってきます。
さて、今日はプログラミングの記事です。
先日来から勉強中のスクレイピングですが、
XPathとBeautiful Soupを併用してスクレイピングをしてみたので本日の記事に。
・テーブル構造でテキストとリンク先URLのセットでスクレイピングしたい(pandasのDataFrameを利用)
・同じテーブル内で複数のa hrefがあり、かつ名前が付与されておらずタグのみで正規表現でもとりにくく、識別しにくい、けど取得したいリンク先URLがだった
→テキスト文章を指定してそのリンク先という指定でとってきたら良さそうだったのでXPathを使うことに
(DataFrameは行数が揃わないとエラーが返ってくるので不要なデータを省いて確実にとりたい)
・Beautiful SoupはXPath使えないけど、lxmlを使えば出来た
【参考にさせていただいたサイト】
http://gci.t.u-tokyo.ac.jp/tutorial/crawling/
http://www.slideshare.net/tushuhei/python-xpath
http://qiita.com/tamonoki/items/a341657a86ff7a945224
#coding: utf-8 from bs4 import BeautifulSoup import urllib2 import pandas as pd import time import lxml.html aaa = [] bbb = [] for page in range(1,2): url = "http://www.~~~" + str(page) html = urllib2.urlopen(url) html2 = urllib2.urlopen(url) soup = BeautifulSoup(html, "lxml") dom = lxml.html.fromstring(html2.read()) for o1 in soup.findAll("td", class_="xx"): aaa.append(o1.string) for o2 in dom.xpath(u"//a[text()='xxx']/@href"): #xxxの部分をテキスト指定でhrefを取得 bbb.append(o2) time.sleep(2) df = pd.DataFrame({"aaa":aaa, "bbb":bbb}) print(df) df.to_csv("xxxx.csv", index=False, encoding='utf-8')
簡単ですが、今日は以上です。