今天爱分享给大家带来[python爬虫]利用xpath清洗数据之html数据清洗【附完整代码】,希望大家能够喜欢。
现在我们面对一些爬虫数据,特别是对于web网页的爬取的时候,网页总有一些不规整的数据来导致拿数据的麻烦,比如如下这种
111
222
333
444
eeeeeeeeeeee
555
aabbccddd
我只想拿到111,222,333,444,555这些有效的信息,因为有些p标签里面会引入script元素,导致我们还要在后期清洗,比较麻烦
分析
首先拿到问题我们就可以本能的想至少两种方式,如果当成是文本处理,使用排除掉script这些文本,另外我们可以直接移除掉这些script元素,这里我不推荐使用正则,毕竟我们拿到一个特定的环境,比如lxml 库就可以很轻松的处理这些文档,使用正则后期维护困难,另外,你过两个星期之后你也不会知道你当时写的正则是什么意思
解决
还是直接上代码吧
# -*- coding: utf-8 -*-
from lxml import html
from lxml.html.clean import Cleaner
html_str = """
111111
222222
333333
44444
eeeeeeeeeeee
665666
aabbccddd
"""
def clean_script():
cleaner = Cleaner()
cleaner.javascript = True # This is True because we want to activate the javascript filter
cleaner.style = True # clean the style element
tree = html.fromstring(html_str)
print html.tostring(cleaner.clean_html(tree))
def remove_node():
tree = html.fromstring(html_str)
ele = tree.xpath('//script')
for e in ele:
e.getparent().remove(e)
print html.tostring(tree)
if __name__ == '__main__':
remove_node()
输出结果
111111
222222
333333
44444
665666
总结
本次主要介绍了常见的html 数据清洗方法,介绍了lxml 一些常用操作和方法,希望对于大家清洗数据的时候有帮助