什么是网页数据采集
简单说,就是用程序自动访问网页,提取你需要的信息,保存下来。比如:
• 采集商品价格,做竞品分析
• 采集招聘信息,做行业薪资报告
• 采集新闻标题,做舆情监控
• 采集论文摘要,做文献综述
Python做这件事有两个神器:requests负责"打开网页",BeautifulSoup负责"提取内容"。
基础:获取网页内容
import requests
# 最简单的请求
response = requests.get("https://example.com")
print(response.status_code) # 200表示成功
print(response.text[:500]) # 打印前500个字符
# 带请求头(模拟浏览器)
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}
response = requests.get("https://example.com", headers=headers)
# 检查是否成功
if response.status_code == 200:
html = response.text
print("获取成功")
else:
print(f"请求失败:{response.status_code}")
解析HTML:提取你需要的数据
from bs4 import BeautifulSoup
html = """
Python编程从入门到实践
¥89.00
流畅的Python
¥139.00
"""
soup = BeautifulSoup(html, "html.parser")
# 找所有商品
products = soup.find_all("div", class_="product")
for p in products:
title = p.find("h3", class_="title").text
price = p.find("span", class_="price").text
author = p.find("span", class_="author").text
print(f"书名:{title}")
print(f"价格:{price}")
print(f"作者:{author}")
print("---")
实战:采集新闻网站标题
import requests
from bs4 import BeautifulSoup
import pandas as pd
import time
def scrape_news(site_url):
"""采集新闻网站标题和链接"""
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
}
response = requests.get(site_url, headers=headers)
soup = BeautifulSoup(response.text, "html.parser")
news_list = []
# 根据实际网页结构调整选择器
for item in soup.find_all("a"):
title = item.get_text(strip=True)
link = item.get("href", "")
# 过滤:标题长度合理,链接是http开头
if len(title) > 8 and link.startswith("http"):
news_list.append({
"标题": title,
"链接": link
})
return news_list
# 采集并保存
news = scrape_news("https://news.example.com")
df = pd.DataFrame(news)
df.to_excel("新闻采集.xlsx", index=False)
print(f"采集到 {len(news)} 条新闻")
数据存储:保存到Excel
import pandas as pd
def save_to_excel(data_list, filename):
"""将采集的数据保存到Excel"""
df = pd.DataFrame(data_list)
# 设置列宽
with pd.ExcelWriter(filename, engine="openpyxl") as writer:
df.to_excel(writer, index=False, sheet_name="数据")
# 调整列宽
worksheet = writer.sheets["数据"]
for i, col in enumerate(df.columns):
max_len = max(df[col].astype(str).map(len).max(), len(col)) + 2
worksheet.column_dimensions[chr(65+i)].width = min(max_len, 50)
print(f"数据已保存到 {filename}")
# 使用
data = [
{"商品名": "Python书", "价格": 89, "评分": 4.8},
{"商品名": "键盘", "价格": 299, "评分": 4.5},
]
save_to_excel(data, "采集结果.xlsx")
注意事项
合法性:只采集公开信息,不采集需要登录的隐私数据。
频率控制:每次请求间隔1-3秒(time.sleep),不要给目标网站造成负担。
robots.txt:访问网站根目录的robots.txt,了解哪些页面允许采集。
数据准确性:采集后务必检查数据质量,处理缺失值和异常值。