本文对比了 Parsel 与 BeautifulSoup 两种常用 Python HTML 解析库在性能、用法、易用性和生态上的差异。通过在 eastmoney.com 站点的实战案例,分别用两者实现财经新闻及数据的爬取,演示如何配置爬虫代理 IP以及对抓取结果的分类存储。全文分为四大模块:
Parsel 基于 lxml,支持 XPath 与 CSS Selector,适合对性能要求较高且习惯使用 XPath 的场景。
import requests
from parsel import Selector
# == 代理 IP 配置(亿牛云爬虫代理示例 www.16yun.cn) ==
proxy_host = "proxy.16yun.cn"
proxy_port = "12345"
proxy_user = "16YUN"
proxy_pass = "16IP"
proxy_template = f"http://{proxy_user}:{proxy_pass}@{proxy_host}:{proxy_port}"
proxies = {
"http": proxy_template,
"https": proxy_template,
}
# == 请求头和 Cookie 设置 ==
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
"Accept-Language": "zh-CN,zh;q=0.9",
}
cookies = {
"device_id": "xxxxxxxxxxxx",
"other_cookie": "value"
}
def fetch_with_parsel(url):
"""
使用 Parsel 结合 requests 进行页面抓取与解析
"""
resp = requests.get(url, headers=headers, cookies=cookies,
proxies=proxies, timeout=10)
resp.encoding = resp.apparent_encoding
sel = Selector(resp.text)
# 抓取新闻条目列表
items = sel.xpath('//div[@id="quote_right"]/div[contains(@class,"newsList")]/ul/li')
results = []
for li in items:
title = li.xpath('.//a/text()').get()
link = li.xpath('.//a/@href').get()
time = li.xpath('.//span/text()').get()
results.append({"title": title, "url": link, "time": time})
return results
if __name__ == "__main__":
url = "https://www.eastmoney.com/"
news = fetch_with_parsel(url)
# 简单分类存储:按今日 / 非今日分组
import datetime
today = datetime.datetime.now().strftime("%m-%d")
grouped = {"today": [], "others": []}
for n in news:
if today in n["time"]:
grouped["today"].append(n)
else:
grouped["others"].append(n)
print("今日财经新闻:", grouped["today"])
BeautifulSoup API 简洁,支持多种解析器,社区活跃,适合快速开发和维护。
import requests
from bs4 import BeautifulSoup
# == 代理 IP 配置(同上) ==
proxies = {
"http": proxy_template,
"https": proxy_template,
}
# == 请求头和 Cookie 设置(同上) ==
headers = headers
cookies = cookies
def fetch_with_bs4(url):
"""
使用 BeautifulSoup 结合 requests 进行页面抓取与解析
"""
resp = requests.get(url, headers=headers, cookies=cookies,
proxies=proxies, timeout=10)
resp.encoding = resp.apparent_encoding
soup = BeautifulSoup(resp.text, 'lxml')
# 抓取新闻条目列表
ul = soup.select_one('div#quote_right div.newsList ul')
results = []
for li in ul.find_all('li'):
a = li.find('a')
span = li.find('span')
results.append({
"title": a.get_text(strip=True),
"url": a['href'],
"time": span.get_text(strip=True)
})
return results
if __name__ == "__main__":
url = "https://www.eastmoney.com/"
news = fetch_with_bs4(url)
# 同样的分类存储逻辑
import datetime
today = datetime.datetime.now().strftime("%m-%d")
grouped = {"today": [], "others": []}
for n in news:
(grouped["today"] if today in n["time"] else grouped["others"]).append(n)
print("今日财经新闻:", grouped["today"])
项目 | Parsel(lxml) | BeautifulSoup(lxml) |
---|---|---|
解析速度 | 更快 | 略慢 |
语法灵活性 | XPath + CSS | CSS Selector |
上手难度 | 中等(需 XPath 知识) | 低(API 直观) |
社区及文档 | 较少 | 丰富 |
┌─────────────┐
│ 核心主题 │
│ Parsel vs BS│
└────┬────────┘
│
┌───────────────────────┴───────────────┐
│ │
┌────┴──────┐ ┌──────┴──────┐
│ Parsel │ │BeautifulSoup│
│ 路线 │ │ 路线 │
└───┬───────┘ └──── ─┬──────┘
│ │
─────┴─────┐ ┌────┴────┐
│ 性能高 │ │ API 简洁 │
└───────────┘ └─────────┘
│ │
┌─────┴─────┐ ┌────┴─────┐
│ XPath/CSS │ │CSS Selector│
└───────────┘ └──────────┘
通过以上全方位对比和实战演示,相信您能根据项目需求,在 Parsel 和 BeautifulSoup 之间做出最适合的选型。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有