Pythonを使用して簡単なWebクローラーを実装する
私たちはPythonのrequestsライブラリを使用してHTTPリクエストを送信し、BeautifulSoupライブラリを使用してHTMLコンテンツを解析します。この簡単なWebクローラーは、Webページからすべてのリンクを抽出します。
サンプル
import requests
from bs4 import BeautifulSoup
def simple_web_crawler(url):
# HTTPリクエストを送信
response = requests.get(url)
# リクエストが成功したかどうかを確認します
if response.status_code == 200:
# HTMLコンテンツを解析
soup = BeautifulSoup(response.text, 'html.parser')
# すべてのリンクを検索
links = soup.find_all('a')
# リンクを抽出して出力
for link in links:
href = link.get('href')
if href:
print(href)
else:
print(f"Failed to retrieve the webpage. Status code: {response.status_code}")
# 使用例
simple_web_crawler('https://www.example.com')
from bs4 import BeautifulSoup
def simple_web_crawler(url):
# HTTPリクエストを送信
response = requests.get(url)
# リクエストが成功したかどうかを確認します
if response.status_code == 200:
# HTMLコンテンツを解析
soup = BeautifulSoup(response.text, 'html.parser')
# すべてのリンクを検索
links = soup.find_all('a')
# リンクを抽出して出力
for link in links:
href = link.get('href')
if href:
print(href)
else:
print(f"Failed to retrieve the webpage. Status code: {response.status_code}")
# 使用例
simple_web_crawler('https://www.example.com')
コードの解説:
import requests:インポートrequestsライブラリ。HTTPリクエストの送信に使用します。from bs4 import BeautifulSoup:インポートBeautifulSoupクラス。HTMLコンテンツの解析に使用します。def simple_web_crawler(url)::関数を定義しますsimple_web_crawler、URLをパラメータとして受け取ります。response = requests.get(url):指定されたURLにGETリクエストを送信し、レスポンスをresponse変数に保存します。if response.status_code == 200::リクエストが成功したかどうかを確認します(ステータスコード200は成功を示します)。soup = BeautifulSoup(response.text, 'html.parser'):使用してBeautifulSoupHTMLコンテンツを解析します。links = soup.find_all('a'):すべての<a>タグを検索します。これらのタグは通常リンクを含みます。for link in links::すべてのリンクを繰り返し処理します。href = link.get('href'):各リンクのhref属性を抽出します。if href::存在するかどうかhrefを確認します。print(href):リンクを出力します。else::リクエストが失敗した場合、エラーメッセージを出力します。
出力結果:
コードを実行すると、プログラムは出力します:https://www.example.comページ内のすべてのリンク。具体的な出力結果は、対象のWebページの内容によって異なります。例えば:
https://www.iana.org/domains/example
これは単なる例です。実際の出力は異なる場合があります。
その他の拡張
Python3 サンプル