您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Python如何使用requests+re进行网络数据抓取
## 一、引言
在网络数据抓取领域,Python凭借其丰富的库生态成为开发者首选工具。`requests`库负责高效网络请求,而`re`模块提供正则表达式支持,二者结合可以快速实现从网页获取数据并提取关键信息的工作流。本文将详细介绍如何组合使用这两个工具完成典型爬虫任务。
## 二、环境准备
### 1. 安装requests库
```bash
pip install requests
import requests
import re
from pprint import pprint # 美化输出
url = "https://example.com"
response = requests.get(url)
print(response.status_code) # 200表示成功
html = response.text # 获取文本内容
binary = response.content # 获取字节内容
.
匹配任意字符(除换行符)\d
匹配数字\w
匹配字母/数字/下划线*
0次或多次重复+
1次或多次重复pattern = r'<h1>(.*?)</h1>' # 非贪婪匹配
resp = requests.get("https://www.python.org")
html = resp.text
title_pattern = re.compile(r'<title>(.*?)</title>', re.IGNORECASE)
match = title_pattern.search(html)
if match:
print(f"网页标题: {match.group(1)}")
params = {'q': 'python', 'page': 1}
response = requests.get("https://search.example.com", params=params)
headers = {
'User-Agent': 'Mozilla/5.0',
'Accept-Language': 'zh-CN'
}
requests.get(url, headers=headers)
# 提取所有链接
link_pattern = re.compile(r'href="(https?://.*?)"')
links = link_pattern.findall(html)
pprint(links[:5]) # 打印前5个链接
try:
response = requests.get(url, timeout=5)
response.raise_for_status() # 检查HTTP错误
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")
def safe_extract(pattern, text):
try:
return re.search(pattern, text).group(1)
except AttributeError:
return None
re.compile()
提前编译requests.Session()
复用连接import requests
import re
def scrape_news():
url = "https://news.example.com"
session = requests.Session()
response = session.get(url)
# 提取新闻块
news_pattern = re.compile(r'<div class="news-item">(.*?)</div>', re.DOTALL)
# 提取标题和链接
item_pattern = re.compile(
r'<h2><a href="(.*?)">(.*?)</a></h2>'
)
for news_block in news_pattern.finditer(response.text):
match = item_pattern.search(news_block.group(1))
if match:
print(f"标题: {match.group(2)}\n链接: {match.group(1)}\n")
if __name__ == '__main__':
scrape_news()
requests+re组合提供了轻量级的数据抓取方案,适合快速原型开发和小规模数据采集。对于复杂场景,建议结合xpath或css选择器等更专业的解析工具。掌握这些基础技能后,您可以进一步探索异步请求、代理设置等高级主题。 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。