python - 如何从 html 的 2 个标签中提取文本或替换第一个和最后一个标签
问题描述
我有如下文字
我只是想从
p
标签中提取内容我不想消除
<p>
它们之间的 或任何其他标签
d = "<p><p>{'Area': 'Square',</p>\n<p> <tr> <td>'Flag': 'com'}</p></p>"
我的代码如下
import re
re.sub('<[^<>]+>', '',d)
我的输出是
"{'Area': 'Square',\n\xa0\xa0'Flag': 'com'}"
预期的只是替换第一个p
和最后一个p
标签
"<p>{'Area': 'Square',</p>\n<p> <tr> <td>'Flag': 'com'}</p>"
解决方案
采用
re.sub(r'^<p>(.*)</p>$', r'\1', d, flags=re.S)
请参阅正则表达式证明。
解释
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
<p> '<p>'
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
.* any character except \n (0 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
</p> '</p>'
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string
推荐阅读
- javascript - gmail脚本搜索和自动删除邮件
- button - 如何修改交互式网格上的“保存”操作
- azure-active-directory - 用于读取生日和入职日期的 Microsoft graph api 权限
- java - 如何在java中进行rest api调用并映射响应对象?
- python - Flask 后端没有响应 JS 前端
- python - 如果同一元素在数据框中出现两次?
- jquery - Fullcalendar - 3 天视图
- amazon-web-services - 在 AWS Cognito 用户池中删除用户时触发 Lambda 函数
- rxjs - 可观察到分组和去抖动?
- python - figsize 对 Jupyter Notebook 中的图形没有影响