今日のテキトーBeautifulSoup

久しぶりにBeautifulSoupのドキュメントみたけど、

bs.find('div', 'class_name')

ってやると、属性の値も条件に含められるのね。知らなかった!

あと、http://www.crummy.com/software/BeautifulSoup/documentation.html#arg-attrsで、属性をみれると書いてあって、

soup.findAll(class=="hoge")

ってやってもsyntaxerrorでうまくいかないなーとか3分くらい悩みましたが、classが予約語だからなんだね。そりゃそうだ。
http://www.crummy.com/software/BeautifulSoup/documentation.html#arg-**kwargsにも、

You can use attrs if you need to put restrictions on attributes whose names are Python reserved words, like class, for, or import; or attributes whose names are non-keyword arguments to the Beautiful Soup search methods: name, recursive, limit, text, or attrs itself.

ってちゃんと書いてあるし。

soup.findAll(attrs={'class':'hoge'})

と書くと期待する結果が得られます。


http://ksklog.blog108.fc2.com/blog-entry-280.htmlのリンク先が多すぎてみる気がしなかったので、久しぶりにBeautifulSoup。
実際は以下はipythonで。ラクチン。

import BeautifulSoup
import urllib
bs =  BeautifulSoup.BeautifulSoup(urllib.urlopen('http://ksklog.blog108.fc2.com/blog-entry-280.html'))
lst = [i.get('href') for i in bs.find('div', 'EntryMore').findAll('a')]
# 一つ目のリンクが空だった
lst.pop(0)

def g(url, dir):
    map(lambda url: urllib.urlretrieve(url, dir + url.split('/')[-1]),
        [i.get('src') for i in BeautifulSoup.BeautifulSoup(urllib.urlopen(url)).findAll(
            lambda x: x.name == 'img' and x.get('src') and x.get('src').endswith('jpg'))])
for u in lst:
    g(u, './')