Python内置了 re 模块,无需额外安装。只需安装 requests 用于发送HTTP请求:
pip install requests在写爬虫之前,先掌握最常用的元字符和量词:
符号 | 作用 | 示例 |
|---|---|---|
. | 匹配任意字符(除换行符) | a.c 匹配 "abc" |
* | 前面字符出现0次或多次(贪婪) | ab* 匹配 "a", "ab", "abb" |
+ | 前面字符出现1次或多次(贪婪) | ab+ 匹配 "ab", "abb" |
? | 前面字符出现0次或1次 | ab? 匹配 "a", "ab" |
.*? | 非贪婪匹配(最短匹配) | 提取标签内容时避免"吞并" |
[] | 匹配方括号中任意字符 | [abc] 匹配 "a", "b", "c" |
\d | 匹配数字 | \d+ 匹配 "123" |
\w | 匹配字母、数字、下划线 | \w+ 匹配 "hello123" |
() | 捕获组,提取括号内内容 | (\d{4}) 提取年份 |
^ / $ | 匹配字符串开头/结尾 | ^\d+ 以数字开头 |
关键提示:在爬虫中,
.*?(非贪婪匹配)比.*(贪婪匹配)更常用。贪婪模式会尽可能多地匹配,容易跨越多个标签导致提取错误;非贪婪模式则精准匹配到最近的闭合位置。
import re
# 1. re.findall() - 找到所有匹配项,返回列表(爬虫最常用)
text = "价格:¥99.00 和 ¥199.50"
prices = re.findall(r'¥(\d+\.\d{2})', text)
print(prices) # ['99.00', '199.50']
# 2. re.search() - 搜索第一个匹配项,返回Match对象
result = re.search(r'\d+', "订单号:20250519")
print(result.group()) # '20250519'
# 3. re.match() - 从字符串开头匹配
result = re.match(r'\d+', "2025年是蛇年")
print(result.group()) # '2025'
# 4. re.sub() - 替换匹配内容
text = "Hello, World!"
new_text = re.sub(r'Hello', 'Hi', text)
print(new_text) # 'Hi, World!'
# 5. re.compile() - 预编译正则,提升重复使用时的性能
pattern = re.compile(r'<a href="(.*?)">')
links = pattern.findall(html_content)import requests
import re
import time
def get_html(url):
"""发送请求获取网页HTML"""
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
try:
response = requests.get(url, headers=headers, timeout=5)
response.encoding = response.apparent_encoding
return response.text
except requests.RequestException as e:
print(f"请求失败: {e}")
return None
def extract_links(html):
"""提取所有超链接"""
pattern = r'<a\s+href="(https?://[^"]+)"'
return re.findall(pattern, html)
def extract_images(html):
"""提取所有图片链接"""
pattern = r'<img\s+[^>]*src="([^"]+)"'
return re.findall(pattern, html)
# 主程序
url = 'https://wlt.wvhjasm.com'
html = get_html(url)
if html:
links = extract_links(html)
images = extract_images(html)
print(f"共找到 {len(links)} 个链接,{len(images)} 张图片")
for link in links[:5]:
print(link)import re
html = '''
<div class="product">
<h2 class="product-title">无线蓝牙耳机</h2>
<span class="price">¥299.00</span>
</div>
<div class="product">
<h2 class="product-title">智能手表Pro</h2>
<span class="price">¥1599.00</span>
</div>
'''
# 提取商品标题(非贪婪匹配,精准捕获标签内容)
title_pattern = r'<h2 class="product-title">(.*?)</h2>'
titles = re.findall(title_pattern, html)
# 提取价格
price_pattern = r'¥(\d+\.\d{2})'
prices = re.findall(price_pattern, html)
# 配对输出
for title, price in zip(titles, prices):
print(f'{title}: ¥{price}')
# 输出:
# 无线蓝牙耳机: ¥299.00
# 智能手表Pro: ¥1599.00import re
text = "张三 13812345678 zhangsan@example.com | 李四 15987654321 lisi@test.cn"
# 使用命名分组提取姓名、电话、邮箱
pattern = r'(?P<name>\w+)\s+(?P<phone>1[3-9]\d{9})\s+(?P<email>[\w.-]+@[\w.-]+\.\w+)'
matches = re.finditer(pattern, text)
for m in matches:
print(f"姓名: {m.group('name')}, 电话: {m.group('phone')}, 邮箱: {m.group('email')}")
# 输出:
# 姓名: 张三, 电话: 13812345678, 邮箱: zhangsan@example.com
# 姓名: 李四, 电话: 15987654321, 邮箱: lisi@test.cnimport requests
import re
html = get_html('https://wlt.wvhjasm.com')
links = extract_links(html)
with open('links.txt', 'w', encoding='utf-8') as f:
for link in links:
f.write(link + '\n')
print("链接已保存到 links.txt")当同一个正则表达式需要反复使用时,用 re.compile() 预编译可以显著提升效率:
# 推荐写法
link_pattern = re.compile(r'<a\s+href="(https?://[^"]+)"')
for html_page in html_list:
links = link_pattern.findall(html_page)html = '<div>内容A</div><div>内容B</div>'
# 贪婪匹配 - 会吞并到最后一个</div>
re.findall(r'<div>(.*)</div>', html)
# 结果: ['内容A</div><div>内容B']
# 非贪婪匹配 - 精准匹配每个div内容
re.findall(r'<div>(.*?)</div>', html)
# 结果: ['内容A', '内容B']https://example.com/robots.txt 查看允许爬取的路径time.sleep(1) 避免给服务器造成压力requests.get(url, timeout=5) 防止程序卡死try-except 包裹网络请求正则适合提取格式稳定、结构简单的数据片段(如价格、日期、电话)。对于复杂的嵌套HTML结构,建议使用 BeautifulSoup 或 lxml 等专业解析器,它们能更好地理解DOM树结构,代码也更易维护。
正则表达式是Python爬虫的"瑞士军刀",掌握 re 模块的核心函数和常用元字符,配合非贪婪匹配和分组捕获,就能应对大多数数据提取场景。记住:简单场景用正则,复杂结构用解析器,两者结合才是最高效的爬虫开发策略。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。