ほんじゃらねっと

ダイエット中プログラマのブログ

BeautifulSoupで特定の属性値を持つタグを取得する

下記のようなXMLから rel="next" なタグの href 属性を取得する場合

<?xml version="1.0" encoding="utf-8"?>
<feed version="0.3" xml:lang="ja">
<title>Pirosukeのブックマーク</title>
<link rel="alternate" type="text/html" href="http://b.hatena.ne.jp/piro_suke/" />
<link rel="next" type="application/atom+xml" href="http://b.hatena.ne.jp/piro_suke/atomfeed?of=30" />
</feed>


下記のようなpython処理で取得できる

import urllib2
from BeautifulSoup import BeautifulSoup
res = urllib2.urlopen("XMLのURL").read()
soup = BeautifulSoup(res)
next_tag = soup.find('link', {"rel":'next'})
next_href = next_tag['href']