搜索和替换 HTML 文本,而不是标签 [英] Search and replace HTML Text, not tags

查看:32
本文介绍了搜索和替换 HTML 文本,而不是标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
如何在html中查找/替换文本同时保留 html 标签/结构

我想通过 HTML 文本进行搜索和替换.我不想摆弄标签或其属性,只想摆弄 HTML 文本.我应该如何在 Python 中做到这一点?

I want to search and replace through HTML text. I don't want to fiddle with the tags or their attributes, just the HTML text. How should I do that in Python?

推荐答案

import lxml.etree as et
html=\
"""
<!DOCTYPE html>
<html>
  <head>
    <title>Hello HTML</title>
  </head>
  <body>
    <p>Hello 1</p>
    <p>Hello 2</p>
    <p>Hello 3</p>
    <p>Hello 4</p>
  </body>
</html>
"""
doc = et.fromstring(html)
for i in doc.xpath('.//p[contains(.,"Hello") and not(contains(.,"4"))]'):
    i.text='replaced'
print et.tostring(doc,pretty_print=True)

输出:

<html>
  <head>
    <title>Hello HTML</title>
  </head>
  <body>
    <p>replaced</p>
    <p>replaced</p>
    <p>replaced</p>
    <p>Hello 4</p>
  </body>
</html>

这篇关于搜索和替换 HTML 文本,而不是标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆