[爬虫]python下的xpath清洗数据之html数据清洗

网友投稿 957 2022-05-30

目录

源起

分析

解决

总结

源起

现在我们面对一些爬虫数据,特别是对于web网页的爬取的时候,网页总有一些不规整的数据来导致拿数据的麻烦,比如如下这种

111

222

333

444

555

1

2

3

4

5

6

7

8

9

10

11

12

13

[爬虫]python下的xpath清洗数据之html数据清洗

14

15

16

17

18

19

20

21

111

222

333

444

555

我只想拿到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

665666

""" 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()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53


# -*- coding: utf-8 -*-

from lxml import html

from lxml.html.clean import Cleaner

html_str = """

111111

222222

333333

44444

665666

"""

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

111111

222222

333333

44444

665666

总结

本次主要介绍了常见的html 数据清洗方法,介绍了lxml 一些常用操作和方法,希望对于大家清洗数据的时候有帮助

HTML Python

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:【 MATLAB 】filter 函数介绍 之 Filter Data in Sections
下一篇:深源恒际入选华为云「鲲鹏凌云伙伴计划」 信用报告智能解析产品获兼容性认证
相关文章

 发表评论

暂时没有评论,来抢沙发吧~