对于我的项目,我必须使用python-xpath从html文件中删除选择性内容。select元素可以使用.remove()方法删除,但文件中的内容看起来相同。
如何将修改后的内容再次写入该文件?
不过,如果我尝试使用open().write(etree.tosttring(tree_obj))将相同的树对象写入文件,unicode页面的内容会有所不同吗?有其他方法可以保存修改后的文件吗?
为什么打印树对象后,下面输出中的头标记具有不同的值?
请提出建议。
下面是我的代码示例。示例:我需要删除html页面中的所有div标记。
HTML文件:
<html>
<head>test</head>
<body>
<p>welcome to the world</p>
<div id="one">
<p>one</p>
<div id="one1">one1</div>
<ul>
<li>ones</li>
<li>twos</li>
<li>threes</li>
</ul>
</div>
<div id="hell">
<p>heaven</p>
<div id="one1">one1</div>
<ul>
<li>ones</li>
<li>twos</li>
<li>threes</li>
</ul>
</div>
<input type="text" placeholder="enter something.." />
<input type="button" value="click" />
</body>
</html>
Python文件:
# _*_ coding:utf-8 _*_
import os
import sys
import traceback
import datetime
from lxml import etree, html
import shutil
def process():
fd=open("D:\hello.html")
tree = html.fromstring(fd.read())
remove_tag = '//div'
for element in tree.xpath(remove_tag):
element.getparent().remove(element)
print etree.tostring(tree)
process()
输出:
<html>
<head/><body><p>test
</p>
<p>welcome to the world</p>
<input type="text" placeholder="enter something.."/>
<input type="button" value="click"/>
</body></html>
我没有研究过python,但我曾在库jsoup的帮助下使用Java解析基于html的网站。
Python也有类似的例子。美味的汤。你可以玩这个东西来获得想要的输出。
希望能有所帮助。
您是否尝试过重新使用python的标准库?
import re</br>
re.sub('<.*?>','', '<nb>foobar<aon><mn>')
re.sub('</.*?>','', '</nb>foobar<aon><mn>')
以上两个操作可以组合使用来删除所有html标记。它也可以很容易地修改以删除div标记。