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




我想搜索并替换HTML文本。我不想摆弄标签或标签的属性,而只是HTML文本。我应该如何在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>

09-10 07:06
查看更多