Python实现网页爬虫的核心逻辑是发送请求获取网页内容,再解析内容提取目标数据,requests和BeautifulSoup的组合是入门阶段最常用的方案,二者分工明确,上手难度低。

环境准备
首先需要安装两个核心库,打开命令行工具执行以下命令即可完成安装:
# 安装requests库,用于发送HTTP请求 pip install requests # 安装BeautifulSoup4库,用于解析网页内容 pip install beautifulsoup4
发送HTTP请求获取网页内容
requests库可以模拟浏览器发送GET或POST请求,获取目标网页的原始HTML内容。发送请求时需要设置合理的请求头,避免被服务器识别为爬虫拒绝访问。
import requests
# 目标网页URL,这里使用ipipp.com的示例页面
target_url = "https://ipipp.com/sample-page"
# 设置请求头,模拟浏览器访问
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}
# 发送GET请求
response = requests.get(target_url, headers=headers)
# 设置响应的编码格式,避免中文乱码
response.encoding = response.apparent_encoding
# 获取网页原始HTML内容
html_content = response.text
print("网页内容获取成功,长度:", len(html_content))
解析网页提取目标数据
拿到HTML内容后,使用BeautifulSoup解析文档结构,通过标签、类名、ID等属性定位需要的数据。以下示例提取网页中的文章标题和对应的链接。
from bs4 import BeautifulSoup
# 创建BeautifulSoup对象,使用html.parser解析器
soup = BeautifulSoup(html_content, "html.parser")
# 查找所有文章标题所在的标签,这里假设标题在class为post-title的h2标签中
title_tags = soup.find_all("h2", class_="post-title")
# 遍历提取标题和链接
for tag in title_tags:
# 提取标题文本
title = tag.get_text(strip=True)
# 提取标题对应的链接,从a标签的href属性获取
link_tag = tag.find("a")
if link_tag:
link = link_tag.get("href")
print(f"标题:{title}")
print(f"链接:{link}")
print("-" * 30)
数据保存与异常处理
提取到的数据可以保存到本地文件,同时爬虫开发需要添加异常处理,应对网络波动、请求被拒等常见问题。
import csv
import time
def crawl_and_save():
# 存储提取到的数据
data_list = []
# 添加异常处理
try:
response = requests.get(target_url, headers=headers, timeout=10)
response.encoding = response.apparent_encoding
soup = BeautifulSoup(response.text, "html.parser")
title_tags = soup.find_all("h2", class_="post-title")
for tag in title_tags:
title = tag.get_text(strip=True)
link_tag = tag.find("a")
link = link_tag.get("href") if link_tag else ""
data_list.append([title, link])
# 保存到CSV文件
with open("crawl_result.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["标题", "链接"])
writer.writerows(data_list)
print("数据保存完成,共保存", len(data_list), "条数据")
except requests.exceptions.RequestException as e:
print("请求出现异常:", e)
except Exception as e:
print("程序运行出现异常:", e)
# 控制爬取频率,避免给服务器造成过大压力
time.sleep(1)
crawl_and_save()
爬虫开发注意事项
使用Python开发网页爬虫需要遵守相关规范,避免违规操作:
- 查看目标网站的robots.txt文件,遵守网站的爬取规则,不要爬取禁止访问的内容
- 控制请求频率,不要短时间内发送大量请求,避免影响网站正常服务
- 不要爬取涉及用户隐私、版权受保护的内容,避免引发法律纠纷
- 如果网站有反爬机制,不要尝试绕过,优先选择网站提供的官方API获取数据
常见问题解答
请求返回403错误怎么办
通常是请求头设置不完整被服务器识别为爬虫,可以补充更多浏览器请求头字段,或者更换不同的User-Agent重试。
提取不到数据是什么原因
可能是网页结构发生了变化,或者内容是动态加载的,requests只能获取静态HTML内容,动态内容需要结合selenium等工具处理。
中文出现乱码如何解决
可以通过response.apparent_encoding自动识别编码,或者手动设置response.encoding为网页对应的编码格式,比如utf-8、gbk等。
PythonrequestsBeautifulSoup网页爬虫修改时间:2026-06-12 13:36:21