Webスクレイピングとは
ウェブサイトから特定の情報を抽出する技術のことです。
Webスクレイピングによってウェブサイトから自動でデータを収集することができます。
PythonによるWebスクレイピングの仕方
ライブラリのインストール
まずrequestsとBeautifulSoupをインストールします
!pip install requests beautifulsoup4
requestsとは
requestsは、PythonでHttp通信を行うためのライブラリです
https://github.com/psf/requests
BeautifulSoupとは
BeautifulSoupHTML、XMLを解析するためのライブラリです。
https://www.crummy.com/software/BeautifulSoup/
Webスクレイピングの実例
今回は例としてyahoo news記事のタイトルを取得します
以下がそのコードです
import requests
from bs4 import BeautifulSoup
url = 'https://news.yahoo.co.jp/topics/top-picks'
html_text = requests.get(url).text
soup = BeautifulSoup(html_text, 'html.parser')
for i, item in enumerate(soup.select('.newsFeed_item'), 1):
if title := item.select_one('.newsFeed_item_title'):
print(i, title.text)
それでは順に内容を解説していきます
import requests
from bs4 import BeautifulSoup
まず、先ほどインストールしたrequestsとBeautifulSoupをimportします
url = 'https://news.yahoo.co.jp/topics/top-picks'
html_text = requests.get(url).text
requests.get(url).text
でurlに指定したページのHTMLを取得できます
soup = BeautifulSoup(html_text, 'html.parser')
HTMLを解析します。こうすることによってHTMLの要素を後々取り出せるようになります
for i, item in enumerate(soup.select('.newsFeed_item'), 1):
if title := item.select_one('.newsFeed_item_title'):
print(i, title.text)
まず soup.select('.newsFeed_item')
によってnewsFeed_item
というクラスを持つ要素を取得します
soup.select(‘.newsFeed_item’)によってニュースのリストが取得できます
その中の一つを取り出すと下記のとおりです。

この中でnewsFeed_item_titleとなっているクラスの要素のみをtitle := item.select_one('.newsFeed_item_title')
で取り出します
そして print(i, title.text)
でインデックスとともにタイトル名を出力しています。
実行すると下記のような結果になります
