2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PythonでWebスクレイピングを行うアプリの作り方

Last updated at Posted at 2024-08-05

はじめに

Webスクレイピングは、ウェブサイトからデータを自動的に取得するための技術です。

Pythonはこのタスクに非常に適しており、強力なライブラリが揃っています。

本記事では、Pythonを使用してWebスクレイピングアプリを作成する方法を紹介します。

1. 必要なライブラリのインストール

まず、Webスクレイピングに必要なライブラリをインストールします。主に使用するライブラリは以下の通りです:

  • requests: HTTPリクエストを送信するためのライブラリ
  • BeautifulSoup: HTMLやXMLのパースに使用するライブラリ
  • pandas (オプション): データを整形し、保存するためのライブラリ

以下のコマンドでこれらのライブラリをインストールします。

pip install requests beautifulsoup4 pandas

2. スクレイピング対象のウェブサイトを決定する

スクレイピングを行うためには、対象のウェブサイトと取得したいデータを決定します。本記事では、例として「架空のニュースサイト」を使用します。

3. HTMLコンテンツを取得する

requestsライブラリを使用してウェブサイトからHTMLコンテンツを取得します。

import requests

url = 'https://example.com/news'
response = requests.get(url)

if response.status_code == 200:
    html_content = response.text
else:
    print('Failed to retrieve the webpage.')

4. HTMLコンテンツをパースする

取得したHTMLコンテンツをBeautifulSoupでパースし、必要なデータを抽出します。

from bs4 import BeautifulSoup

soup = BeautifulSoup(html_content, 'html.parser')

# ニュースタイトルを取得する例
titles = soup.find_all('h2', class_='news-title')
for title in titles:
    print(title.text)

5. データの保存(オプション)

データをCSVファイルに保存するために、pandasを使用することができます。

import pandas as pd

data = {'Title': [title.text for title in titles]}
df = pd.DataFrame(data)

df.to_csv('news_titles.csv', index=False)

6. 完全なコード例

以下に、全てのステップを含む完全なコード例を示します。

import requests
from bs4 import BeautifulSoup
import pandas as pd

# スクレイピング対象のURL
url = 'https://example.com/news'

# HTMLコンテンツを取得
response = requests.get(url)
if response.status_code == 200:
    html_content = response.text
else:
    print('Failed to retrieve the webpage.')
    exit()

# HTMLコンテンツをパース
soup = BeautifulSoup(html_content, 'html.parser')

# ニュースタイトルを取得
titles = soup.find_all('h2', class_='news-title')

# データを保存
data = {'Title': [title.text for title in titles]}
df = pd.DataFrame(data)
df.to_csv('news_titles.csv', index=False)

print('Data has been saved to news_titles.csv')

まとめ

Pythonを使用したWebスクレイピングは、非常に強力で柔軟なツールです。

requestsとBeautifulSoupを組み合わせることで、簡単にウェブサイトからデータを抽出し、pandasを使ってデータを整形・保存することができます。

スクレイピングを行う際には、サイトの利用規約を守り、適切なエラーハンドリングを実装することを忘れないようにしましょう。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?