html text search,Search and replace HTML Text, not tags [duplicate]

问题

This question already has answers here:

Closed 6 years ago.Possible Duplicate:

How to find/replace text in html while preserving html tags/structure

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?

回答1:

import lxml.etree as et

html=\

"""

Hello HTML

Hello 1

Hello 2

Hello 3

Hello 4

"""

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)

OUT:

Hello HTML

replaced

replaced

replaced

Hello 4

回答2:

You can try with Re module. Or just use replace function.

But Search and replace is very inefficient processing, if you need to replace on multiple keywords. You should better parse the structure via beautifulSoup or lxml, get the objects, and do some operations on the objects.

来源:https://stackoverflow.com/questions/14134843/search-and-replace-html-text-not-tags

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值