Pythonスクレイピングでデータを取得する方法
Pythonのスクレイピングによるデータ取得は、以下の手順で構成されています。
- 日本語でリクエストすることがあります
- BeautifulSoup4
import requests
from bs4 import BeautifulSoup
- リクエスト
url = "http://example.com" # 要爬取的网页的URL
response = requests.get(url) # 发送GET请求获取网页内容
html_content = response.text # 获取网页的HTML内容
- Beautiful Soup 4
soup = BeautifulSoup(html_content, "html.parser") # 使用HTML解析器解析网页内容
data = soup.find("tag", attrs={"attribute": "value"}) # 根据标签和属性找到特定的数据
- Webの構造と必要とするデータに応じて、適切に抽出処理を実施します。
# 提取文本数据
text_data = data.get_text()
# 提取链接
link_data = data["href"]
# 提取图片链接
img_data = data.find("img")["src"]
# 提取表格数据
table_data = []
table = soup.find("table")
rows = table.find_all("tr")
for row in rows:
cols = row.find_all("td")
cols = [col.get_text() for col in cols]
table_data.append(cols)
- 抽出したデータを保存処理:ファイルなどへの保存、データベース化など
# 保存到文件
with open("data.txt", "w") as file:
file.write(text_data)
# 存储到数据库
import sqlite3
conn = sqlite3.connect("data.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS data (text TEXT, link TEXT, img TEXT)")
cursor.execute("INSERT INTO data VALUES (?, ?, ?)", (text_data, link_data, img_data))
conn.commit()
conn.close()
具体的にPythonでクローラーを使用してデータを収集する手順は、要求やウェブページの構造によって異なります。