提问人:Lexx Luxx 提问时间:8/22/2021 最后编辑:Lexx Luxx 更新时间:8/25/2021 访问量:319
在 Python 中使用 lxml 和 XPath 清理 HTML
Cleanup HTML using lxml and XPath in Python
问:
我正在学习python和lxml工具包。我需要处理本地目录中的多个 .htm 文件(递归)并删除不需要的标签,包括其内容(ID 为“box”、“columnRight”、“adbox”、“footer”、div class=“box”的 div,以及所有样式表和脚本)。 不知道该怎么做。我有列出目录中所有 .htm 文件的代码:
#!/usr/bin/python
import os
from lxml import html
import lxml.html as lh
path = '/path/to/directory'
for root, dirs, files in os.walk(path):
for name in files:
if name.endswith(".htm"):
doc=lh.parse(filename)
所以我需要添加部分,创建一个树,处理html并删除不必要的div,比如
for element in tree.xpath('//div[@id="header"]'):
element.getparent().remove(element)
如何为此调整代码?
HTML 页面示例。
答:
1赞
Jack Fleeting
8/24/2021
#1
如果不查看实际文件,很难分辨,但请尝试以下操作,看看它是否有效:
首先,你不需要两者
from lxml import html
import lxml.html as lh
所以你可以放弃第一个。然后
for root, dirs, files in os.walk(path):
for name in files:
if name.endswith(".htm"):
tree = lh.parse(name)
root = tree.getroot()
for element in root.xpath('//div[@id="header"]'):
element.getparent().remove(element)
评论
0赞
Lexx Luxx
8/24/2021
我测试了,出现错误:另外,应该省略第一次导入还是第二次导入?Traceback (most recent call last): File "./clean.py", line 9, in <module> tree = etree.parse(name) NameError: name 'etree' is not defined
from lxml import html
0赞
Jack Fleeting
8/24/2021
对于第一个问题 - 我的错误;这是一个错别字 - 请参阅编辑版本(更改为 )。至于第二个问题 - 只需要.etree
lh
import lxml.html as lh
0赞
Lexx Luxx
8/24/2021
尝试时,得到 IOError。实际页面示例位于顶部。
1赞
Jack Fleeting
8/24/2021
@triwo 你可能应该把它作为一个单独的问题来问。它与 lxml、xpath 和 html 解析无关,它们是您问题中的标签。
1赞
mzjn
8/25/2021
这是题外话,但现在没有充分的理由使用 Python 2(除非您必须维护遗留的 Python 2 代码库)。
评论
xpath()
tree = html.parse(path)