Python 网页数据爬取实战教程
1. 环境准备
在开始之前,请确保已安装 Python 环境及相关库:
pip install requests beautifulsoup4
2. 核心流程
爬虫的基本流程包括以下四个步骤:
- 获取 URL:明确目标网页地址。
- 发送请求:模拟浏览器发送 HTTP 请求获取源代码。
- 解析 HTML:使用解析库处理返回的文本内容。
- 提取数据:定位并抓取所需信息。
3. 代码实现
以下示例演示如何使用 requests 获取网页源码,并利用 BeautifulSoup 解析列表中的数据。
import requests
from bs4 import BeautifulSoup
def fetch_data(url):
# 设置请求头,模拟浏览器行为
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
try:
response = requests.get(url, headers=headers, timeout=10)
# 自动识别编码,防止乱码
response.encoding = response.apparent_encoding
# 初始化 BeautifulSoup 对象,使用 html.parser
soup = BeautifulSoup(response.text, 'html.parser')
# 假设目标数据在 ul 列表中(根据实际页面结构调整选择器)
items = soup.find_all('ul')
data_list = []
for item in items:
# 进一步定位子元素并提取文本
text = item.get_text(strip=True)
if text:
data_list.append(text)
return data_list
except Exception as e:
print(f"Error: {e}")
return []
if __name__ == '__main__':
target_url = 'https://example.com' # 替换为实际目标网址
results = fetch_data(target_url)
for r in results:
print(r)
4. 调试技巧
- 查看元素结构:在浏览器中按 F12 打开开发者工具,检查目标数据的标签名称、class 或 id。
- 定位路径:使用左上角的箭头工具点击页面对应元素,确认其在 DOM 树中的位置。
- 验证结果:运行脚本后对比控制台输出与网页显示内容是否一致。
5. 注意事项
- 遵守协议:尊重网站的 robots.txt 规则,避免高频访问。
- 异常处理:网络请求可能失败,需添加 try-except 块增强稳定性。
- 数据清洗:提取的文本可能包含多余空白字符,建议使用
.strip()处理。

