使用 python 抓取网页数据时,requests 和 beautifulsoup 是最常用的组合。requests 用于发送 http 请求并获取网页内容,而 beautifulsoup 则用于解析 html 并提取所需数据。1. 安装依赖库:使用 pip install requests beautifulsoup4 或加国内源安装;2. 获取网页内容:通过 requests.get() 方法发送请求,并加入异常处理和 headers 模拟浏览器访问;3. 解析 html:用 beautifulsoup 初始化解析器,利用 find、find_all 和 select 等方法提取数据;4. 注意编码问题、结构不稳定及请求频率控制等小技巧避免踩坑。这套方案适用于静态页面,且简单高效。
想用 python 父取网页数据,requests 和 BeautifulSoup 是最常见、也最容易上手的组合。简单来说,requests 用来下载网页内容,BeautifulSoup 用来解析 HTML 并提取你需要的数据。这套方案适合静态页面,不涉及 JavaScript 渲染。
准备工作:安装依赖库
使用前需要先安装两个库,命令如下:
pip install requests beautifulsoup4
这两个库都很轻量,安装过程一般不会出问题。如果网络不好,可以加国内源,比如清华镜像:
立即学习“Python免费学习笔记(深入)”;
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple requests beautifulsoup4
第一步:获取网页内容(requests)
爬虫的第一步是发送 HTTP 请求,拿到网页的 HTML 内容。requests 的 get 方法就能搞定:
import requests url = 'https://example.com' response = requests.get(url) # 检查是否成功获取 if response.status_code == 200: html_content = response.text else: print("请求失败")
这里需要注意几个点:
-
加入异常处理,比如超时或连接错误:
try: response = requests.get(url, timeout=10) except requests.exceptions.RequestException as e: print(e)
-
有些网站会检测 User-Agent,防止你被拒绝访问,可以加上 headers:
headers = { 'User-Agent': 'Mozilla/5.0 (windows NT 10.0; Win64; x64)' } response = requests.get(url, headers=headers)
第二步:解析HTML并提取数据(BeautifulSoup)
有了 HTML 内容后,下一步就是从中提取有用的信息。BeautifulSoup 提供了非常方便的方法来查找标签和内容。
from bs4 import BeautifulSoup soup = BeautifulSoup(html_content, 'html.parser') # 示例:提取所有链接 for link in soup.find_all('a'): print(link.get('href')) # 示例:提取特定标题 title = soup.find('h1').text print(title)
常用的查找方法包括:
举个实际例子,比如你想提取某个新闻网站的文章标题和正文,可以这样写:
title = soup.find('h1', class_='article-title').text.strip() content = soup.find('div', id='article-content').text.strip()
注意类名要用 class_,因为 class 是 Python 关键字。
小技巧:避免踩坑
这个组合虽然简单,但还是有几个容易忽略的地方:
-
编码问题:有时返回的内容乱码,记得检查响应头的编码方式:
response.encoding = response.apparent_encoding
-
结构不稳定:网页结构可能经常变,建议写代码时多加判断,比如:
title_tag = soup.find('h1') title = title_tag.text if title_tag else '未知标题'
-
不要太快请求:频繁访问可能会被封 IP,适当加点延迟:
import time time.sleep(1) # 每次请求间隔1秒
基本上就这些。整个流程下来,你会发现 requests 负责“拿”,BeautifulSoup 负责“挑”,配合起来很顺手。对于大多数静态网页来说,这套组合已经够用了,也不需要太复杂的配置。