madokaのブログ

勉強したことのoutput先として使ってます。内容はpythonがらみが多いかもです。

pyqueryとBeautifulSoupの比較

lambdaにてpyqueryを使ったものをアップロードして利用しようとしたところ、エラーが発生してしまいました。pyquery中のetreeというパッケージが存在しないとのこと。おそらくetreeのデータをsite-packagesの中に組み込めば動くようになると考えられるのですが、普通の行動してエラー吐かれた事実に面倒くささを感じ、スクレイピングを行うapiをBeautifulSoupに変更することにしました。その時に発生した変更分などから、どんな違いがあるのか簡単まとめてみました。

スクレイピングの準備

pyquery

from pyquery import PyQuery

url = 'https://…'
query = PyQuery(url, parser='html')

BeautifulSoup

from urllib.request import urlopen
from bs4 import BeautifulSoup

url = 'https://…'
soup = BeautifulSoup(urlopen(url), 'html.parser')

タグによる指定

pyquery

query(‘header’)

BeautifulSoup

soup.find_all('header')

idによる指定

pyquery

query('#a')

BeautifulSoup

soup.find_all(id='a')

class名による指定

pyquery

query('.clazz')

BeautifulSoup

soup.find_all(class_='clazz')

属性による指定

pyquery

query('[href=\'https://….\']')

BeautifulSoup

soup.find_all(attrs={'href':'https://….'})
soup.find_all(href='https://….')

中身を取得する

pyquery

element.attr('href')
element.attr('class')

BeautifulSoup

element.get('href')
element.get('class')

要素の中の文章を取得する

pyquery

element.text()

BeautifulSoup

element.text

少しコメント

pyqueryの指定方法は、cssセレクタのようです。一方、BeautifulSoupは使えないのかというとそういうわけではありません。selectというmethodを使えば、cssセレクタによる指定も可能です。

まとめ

スクレイピングで書くコードはどのapiを使っても書き方に大きな変化はないなという印象を受けました。