网站首页 > 博客文章 正文
在 Python 中,Requests 和 BeautifulSoup 是开发网络爬虫的基础工具,分别负责发送 HTTP 请求和解析网页内容。以下是它们的功能和使用示例。
1. Requests:简化 HTTP 请求
特点
- 提供友好的 API 接口,用于发送 GET、POST 等 HTTP 请求。
- 支持自动处理 Cookie、Session 和认证。
基础用法
import requests
# 发送 GET 请求
response = requests.get("https://example.com")
print(response.status_code) # 输出 HTTP 状态码
print(response.text) # 输出网页内容
带参数和头部的请求
python
url = "https://httpbin.org/get"
params = {"key": "value"}
headers = {"User-Agent": "Mozilla/5.0"}
response = requests.get(url, params=params, headers=headers)
print(response.json()) # 解析 JSON 数据
异常处理
python
try:
response = requests.get("https://example.com", timeout=5)
response.raise_for_status() # 检查响应状态
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")
2. BeautifulSoup:解析网页内容
特点
- 基于 HTML 或 XML 的文档解析。
- 提供简洁的 API 获取页面的特定元素。
安装
bash
pip install beautifulsoup4
基础用法
python
from bs4 import BeautifulSoup
html = """
<html>
<head><title>Example</title></head>
<body>
<p class="content">Hello, World!</p>
</body>
</html>
"""
soup = BeautifulSoup(html, "html.parser")
print(soup.title.string) # 输出 'Example'
print(soup.find("p", class_="content").text) # 输出 'Hello, World!'
从网页提取数据
python
import requests
from bs4 import BeautifulSoup
url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
# 提取所有链接
links = [a["href"] for a in soup.find_all("a", href=True)]
print(links)
3. Requests 与 BeautifulSoup 的结合
以下是一个完整的爬虫示例,用于获取指定网站的标题和所有链接:
python
import requests
from bs4 import BeautifulSoup
url = "https://example.com"
headers = {"User-Agent": "Mozilla/5.0"}
response = requests.get(url, headers=headers)
if response.status_code == 200:
soup = BeautifulSoup(response.text, "html.parser")
title = soup.title.string # 获取页面标题
links = [a["href"] for a in soup.find_all("a", href=True)] # 获取所有链接
print(f"页面标题: {title}")
print(f"页面链接: {links}")
else:
print(f"请求失败,状态码: {response.status_code}")
4. 进阶功能
分页爬取
利用 URL 的查询参数爬取多页内容:
python
base_url = "https://example.com/page="
for i in range(1, 6): # 爬取前 5 页
response = requests.get(base_url + str(i))
if response.ok:
soup = BeautifulSoup(response.text, "html.parser")
print(f"第 {i} 页内容已抓取")
处理动态网页
对于需要处理 JavaScript 渲染的页面,使用 Selenium 或 Playwright 辅助加载。
5. 常见问题与解决方法
- 请求被拒绝:尝试添加 User-Agent 头部,模拟真实用户请求。
- 反爬虫机制:控制请求频率,使用代理 IP。
- 解析失败:检查页面结构变化,更新选择器。
通过 Requests 和 BeautifulSoup 的组合,可以快速开发功能强大的网络爬虫,轻松实现数据抓取和处理任务!
猜你喜欢
- 2024-12-18 轻松解析数据!你不可不知的Python宝藏库——parser模块
- 2024-12-18 基于Google Gemini的网页抓取 谷歌怎么抓取网页里的图片
- 2024-12-18 使用Python抓取欧洲足球联赛数据 python 竞彩
- 2024-12-18 网络爬虫——从网站中提取有用的数据
- 2024-12-18 网上售卖几百一月的微信机器,Python几十行代码就能搞定
- 2024-12-18 一个Python编写的小说下载器 用python写小说
- 2024-12-18 LangChainV0.2-进阶教程:构建一个RAG应用
- 2024-12-18 Python应用短文,如何自制一个简易的网络爬虫
- 2024-12-18 机器学习第五发:BS教你如何解析网页,规整数据?
- 2024-12-18 python3的bs4模块的安装、介绍 python中bs4模块
你 发表评论:
欢迎- 367℃用AI Agent治理微服务的复杂性问题|QCon
- 358℃初次使用IntelliJ IDEA新建Maven项目
- 357℃手把手教程「JavaWeb」优雅的SpringMvc+Mybatis整合之路
- 351℃Maven技术方案最全手册(mavena)
- 348℃安利Touch Bar 专属应用,让闲置的Touch Bar活跃起来!
- 346℃InfoQ 2024 年趋势报告:架构篇(infoq+2024+年趋势报告:架构篇分析)
- 345℃IntelliJ IDEA 2018版本和2022版本创建 Maven 项目对比
- 342℃从头搭建 IntelliJ IDEA 环境(intellij idea建包)
- 最近发表
- 标签列表
-
- powershellfor (55)
- messagesource (56)
- aspose.pdf破解版 (56)
- promise.race (63)
- 2019cad序列号和密钥激活码 (62)
- window.performance (66)
- qt删除文件夹 (72)
- mysqlcaching_sha2_password (64)
- ubuntu升级gcc (58)
- nacos启动失败 (64)
- ssh-add (70)
- jwt漏洞 (58)
- macos14下载 (58)
- yarnnode (62)
- abstractqueuedsynchronizer (64)
- source~/.bashrc没有那个文件或目录 (65)
- springboot整合activiti工作流 (70)
- jmeter插件下载 (61)
- 抓包分析 (60)
- idea创建mavenweb项目 (65)
- vue回到顶部 (57)
- qcombobox样式表 (68)
- vue数组concat (56)
- tomcatundertow (58)
- pastemac (61)
本文暂时没有评论,来添加一个吧(●'◡'●)