0
0

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 2025-02-21

PythonでWebスクレイピングを始めよう!

はじめに

Webスクレイピングとは、プログラムを使ってウェブサイトのデータを取得し、自動的に解析する技術です。本記事では、PythonのBeautifulSoupとrequestsを使用して簡単なスクレイピングを実装する方法を紹介します。

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

以下のコマンドを実行して、必要なライブラリをインストールしましょう。

pip install requests beautifulsoup4

簡単なスクレイピングの実装

Pythonを使って、あるウェブページのタイトルを取得する基本的なコードを書いてみましょう。

import requests
from bs4 import BeautifulSoup

スクレイピング対象のURL

url = "https://qiita.com/"

ページのHTMLを取得

response = requests.get(url)

BeautifulSoupを使って解析

soup = BeautifulSoup(response.text, "html.parser")

タイトルを取得

title = soup.title.text
print("ページのタイトル:", title)

応用編:特定のデータを取得する

例えば、Qiitaの記事一覧のタイトルを取得するには、HTMLの構造を調査し、適切なタグを指定します。

記事のタイトル一覧を取得

titles = soup.find_all("h1")
for i, title in enumerate(titles, 1):
print(f"{i}: {title.text}")

注意点

Webスクレイピングを行う際は、対象サイトの利用規約を必ず確認し、サーバーに負担をかけないようにしましょう。また、robots.txtをチェックすることも重要です。

robots.txtを確認

robots_url = "https://qiita.com/robots.txt"
robots_response = requests.get(robots_url)
print(robots_response.text)

まとめ

本記事では、Pythonを使った基本的なWebスクレイピングの手順を紹介しました。実際のプロジェクトでは、データの保存やAPIの利用など、さらに応用的な手法も検討してみてください。

今後もPythonを活用して効率的なデータ収集を行いましょう!

0
0
1

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?