Skip to content

数据提取

  • 对抓取的数据进行提取,得到需要的信息。

数据类型

结构化数据

  • 结构化数据是指数据具有一定的格式,例如 json、xml 等。

非结构化数据

  • 非结构化数据是指数据没有一定的格式,例如 html、txt 等。

半结构化数据

  • 半结构化数据是指数据具有一定的格式,但是不是结构化数据,例如 csv、excel 等。

json 数据处理

json模块

json模块提供了loadsdumps方法,分别用于将 json 字符串解析成 python 对象,以及将 python 对象解析成 json 字符串。

python
import json

# json字符串解析成python对象
data = json.loads('{"name": "zhangsan", "age": 18}')

# python对象解析成json字符串
json_str = json.dumps(data)

jsonpath模块

  • 安装模块pip install jsonpath
  • jsonpath模块提供了jsonpath方法,用于从 json 字符串中提取数据。
python
import json
import jsonpath

json_str = """{
    "name": "zhangsan",
    "age": 18
}"""
print(json_str)
# 从json字符串中提取数据
data = jsonpath.jsonpath(json.loads(json_str), '$.name')
print(data)

解析 html/xml 数据

lxml模块

  • lxml模块是一个用于解析 html/xml 的模块,采用xpath语言查找路径。
  • 安装模块pip install lxml
  • 参考文档:https://www.w3cschool.cn/lxml
python
from lxml import etree

html_str = """
<html>
	<body>
		<div>
		    <ul>
		         <li class="item-0"><a href="link1.html">first item</a></li>
		         <li class="item-1"><a href="link2.html">second item</a></li>
		         <li class="item-inactive"><a href="link3.html">third item</a></li>
		         <li class="item-1"><a href="link4.html">fourth item</a></li>
		         <li class="item-0"><a href="link5.html">fifth item</a></li>
		     </ul>
		</div>
	</body>
</html>
"""
# 获取html对象
obj = etree.HTML(html_str)
# 基于xpath获取dom
dom = obj.xpath('//ul/li/a')
# 遍历dom
for item in dom:
	# 获取属性
    print(item.get('href'))
	# 获取文本
    print(item.text)
	# 获取父节点 class 名称
    print(item.getparent().get('class'))