PythonでWEBスクレイピングをする方法(初心者)
Pythonに関しては初心者なので、シンプルな方法で、WEBスクレイピングをします。
「Requests」を使ってWebページを取得し、「Beautiful Soup」を使ってHTMLを抽出する方法を試してみます。
インストール
まずは、Pythonのライブラリをインストールします。
●Requests
pip install requests
●Beautiful Soup
pip install beautifulsoup4
サンプルソース
# ライブラリ読み込み import requests from bs4 import BeautifulSoup # 読み込むURL url = "http://www.example.com/" # HTMLデータの取得 response = requests.get(url) response.encoding = response.apparent_encoding # HTMLデータの解析 bs = BeautifulSoup(response.text, 'html.parser') # Aタグを全て取得 idxs = bs.find_all("a") for idx in idxs: print(idx.string) # リンク文字列を出力 print(idx.get('href')) # URLを出力
実行結果
このブログのトップページをWEBスクレイピングしてみました。
Aタグの文字列とリンクが表示できました。
ジプログホームホームホームプログラミング https://jipulog.com/category/programming/ 調査したこと https://jipulog.com/category/chousa/ お問い合わせ https://jipulog.com/contact/ プライバシーポリシープライバシーポリシー. . .
pythonを実行すると何故かこのエラーがで出て実行できなくなってしまいました。
「ImportError: cannot import name 'BeautifulSoup’」
実行ファイル名を「html.py」としていたため、名前がかぶってエラーが発生してしまったようです。
ファイル名を変更したら無事に動きました。
「ImportError: cannot import name 'BeautifulSoup’」
実行ファイル名を「html.py」としていたため、名前がかぶってエラーが発生してしまったようです。
ファイル名を変更したら無事に動きました。
検索メソッド
find() マッチしたものの最初の一つを返す。
find_all() マッチしたものをすべて返す。
select() 特殊な検索ができる。
●検索例
# タグ検索 print(bs.find_all("div")) # id検索 print(bs.find_all(id="dummy-id")) # class検索 print(bs.find_all(class_="dummy-class")) # URL検索 print(bs.find_all(href="https://jipulog.com")) # 文字列検索 print(bs.find_all(string="ジプログ")) # 複数条件検索 print(bs.find_all("h1", id="test-id", string="ジプログ")) # 属性を取得 print(bs.div.get("id")) # テキストを取得 print(bs.a.string) print(bs.find(class_="dummy-class").string) #divのdummy-classクラス print(soup.select("div > .dummy-class"))
参考サイト
https://www.sejuku.net/blog/51241
http://python.zombie-hunting-club.com/entry/2017/11/08/192731