python 小案例正则表达式

正则表达式是一种用于匹配、查找和替换文本的强大工具。在提取网页中的目标数据时,可以使用正则表达式来搜索和匹配特定模式的文本。

以下是一个使用正则表达式提取网页中的目标数据的示例代码:

复制代码
import re

# 网页源代码
html = """
<div class="title">正则表达式教程</div>
<div class="content">这是一篇关于正则表达式的教程。</div>
<div class="author">作者:小明</div>
"""

# 提取标题
title_pattern = r'<div class="title">(.*?)</div>'
title_match = re.search(title_pattern, html)
if title_match:
    title = title_match.group(1)
    print("标题:", title)

# 提取内容
content_pattern = r'<div class="content">(.*?)</div>'
content_match = re.search(content_pattern, html)
if content_match:
    content = content_match.group(1)
    print("内容:", content)

# 提取作者
author_pattern = r'<div class="author">(.*?)</div>'
author_match = re.search(author_pattern, html)
if author_match:
    author = author_match.group(1)
    print("作者:", author)

运行以上代码,将会输出:

复制代码
标题: 正则表达式教程
内容: 这是一篇关于正则表达式的教程。
作者: 小明

在上述代码中,我们使用了re.search()函数来搜索匹配特定模式的文本。正则表达式的模式使用了特定的语法符号,如.表示任意字符,*表示前面的字符可以重复任意次数,.*?表示非贪婪匹配,()表示分组。通过使用分组,我们可以方便地提取匹配到的目标数据。

需要注意的是,当处理复杂的HTML结构时,正则表达式可能无法很好地处理,建议使用专门的HTML解析库(如BeautifulSoup)来提取网页中的数据。

本文由mdnice多平台发布

相关推荐
茶栀(*´I`*)几秒前
Python网络机器人入门:从Robots协议、网页结构到Requests库的基础实践
网络·python·机器人
SunnyDays10118 分钟前
如何使用 Python 添加和编辑 Excel VBA 宏(无需安装 Excel)
开发语言·python·excel·vba
2601_962295999 分钟前
Python+Appium 自动化测试:从基础语法到 PO 模式设计,构建稳定测试框架
自动化测试·python·appium·测试框架·po模式
开源量化GO9 分钟前
先确认策略想法能不能变成规则
人工智能·python
拜托多多指教10 分钟前
【Pytest框架学习】分层架构
python·pytest
zhanghaha131418 分钟前
Python进阶教程:24_Markdown 转 HTML 零基础超详细教程
开发语言·python·html
2601_9622998827 分钟前
python脚本如何单元测试
python·单元测试·pytest·unittest·mock对象
女神下凡29 分钟前
PyCharm 2026破解激活
ide·python·pycharm
DeepVisionary36 分钟前
视频生成首次按秒收费:Gemini Omni 1.1 Flash 4K 每秒 0.3 美元,360p 到 4K 全档位定价
python·自动化
智擎GEO1 小时前
中山GEO优化哪个靠谱
人工智能·python