您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Python中怎么利用正则表达式从网页摘取信息
## 1. 正则表达式基础
### 1.1 什么是正则表达式
正则表达式(Regular Expression)是一种用于匹配字符串中字符组合的模式,通过特定语法规则可以高效地进行文本搜索、替换和提取操作。
### 1.2 基本元字符
- `.` 匹配任意单个字符(除换行符)
- `\d` 匹配数字(等价于[0-9])
- `\w` 匹配字母数字和下划线
- `\s` 匹配空白字符
- `^` 匹配字符串开头
- `$` 匹配字符串结尾
### 1.3 量词
- `*` 0次或多次
- `+` 1次或多次
- `?` 0次或1次
- `{n}` 精确n次
- `{n,}` 至少n次
- `{n,m}` n到m次
## 2. Python正则模块re
### 2.1 常用方法
```python
import re
# 查找第一个匹配
re.search(pattern, string)
# 查找所有匹配
re.findall(pattern, string)
# 替换匹配内容
re.sub(pattern, repl, string)
# 预编译正则对象
compiled_pattern = re.compile(pattern)
使用()
创建捕获组:
text = "Date: 2023-08-15"
match = re.search(r"Date: (\d{4}-\d{2}-\d{2})", text)
if match:
print(match.group(1)) # 输出:2023-08-15
import requests
url = "https://example.com"
response = requests.get(url)
html_content = response.text
title_pattern = r"<title>(.*?)</title>"
title = re.search(title_pattern, html_content, re.IGNORECASE)
if title:
print("网页标题:", title.group(1))
link_pattern = r'href=["\'](.*?)["\']'
links = re.findall(link_pattern, html_content)
print("所有链接:", links)
假设需要提取商品信息:
<div class="product">
<h3>Product Name</h3>
<span class="price">$19.99</span>
</div>
提取代码:
product_pattern = r'<div class="product">.*?<h3>(.*?)</h3>.*?<span class="price">(.*?)</span>'
products = re.findall(product_pattern, html_content, re.DOTALL)
for name, price in products:
print(f"商品: {name}, 价格: {price}")
默认量词是贪婪的,添加?
转为非贪婪:
# 贪婪匹配
re.search(r'<div>.*</div>', "<div>a</div><div>b</div>").group()
# 结果: <div>a</div><div>b</div>
# 非贪婪匹配
re.search(r'<div>.*?</div>', "<div>a</div><div>b</div>").group()
# 结果: <div>a</div>
使用re.MULTILINE
标志使^
和$
匹配每行开头结尾:
text = "Line1\nLine2\nLine3"
re.findall(r'^Line\d', text, re.MULTILINE)
# 结果: ['Line1', 'Line2', 'Line3']
使用re.IGNORECASE
标志:
re.search(r'python', 'PYTHON', re.IGNORECASE).group()
# 结果: 'PYTHON'
def debug_regex(pattern, string):
try:
print("匹配结果:", re.findall(pattern, string))
except re.error as e:
print("正则错误:", e)
debug_regex(r'(\d+', "123") # 会捕获到未闭合括号错误
正则表达式不适合处理:
- 嵌套标签(如<div><div></div></div>
)
- 格式错误的HTML
- 复杂的DOM结构
建议复杂场景使用BeautifulSoup或lxml:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_content, 'html.parser')
titles = [h3.text for h3 in soup.find_all('h3')]
.*?
.
应写为\.
)import re
import requests
def extract_news(url):
# 获取网页内容
response = requests.get(url)
html = response.text
# 预编译正则表达式
title_re = re.compile(r'<h2 class="news-title">(.*?)</h2>')
date_re = re.compile(r'<span class="date">(.*?)</span>')
content_re = re.compile(r'<div class="content">(.*?)</div>', re.DOTALL)
# 提取数据
news = []
for match in re.finditer(
r'<article>.*?<h2 class="news-title">(.*?)</h2>.*?<span class="date">(.*?)</span>.*?<div class="content">(.*?)</div>.*?</article>',
html,
re.DOTALL
):
news.append({
'title': match.group(1),
'date': match.group(2),
'content': re.sub(r'<.*?>', '', match.group(3)).strip()
})
return news
# 使用示例
news_list = extract_news("https://news.example.com")
for news in news_list:
print(f"{news['date']} - {news['title']}")
print(news['content'][:100] + "...")
print()
正则表达式是Python网页数据抓取的利器,但需要注意: 1. 简单结构用正则,复杂HTML用解析库 2. 编写模式时考虑边界情况 3. 重要数据建议多重验证 4. 遵守网站的robots.txt规定
通过合理运用正则表达式,可以高效完成各种网页信息提取任务,为数据分析、爬虫开发等场景提供基础支持。 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。