提示:文末有福利!最新Python爬虫资料/学习指南>>戳我直达

文章目录

  • 前言
  • JSON
    • 1. json.loads()
    • 2. json.dumps()
    • 3. json.dump()
    • 4. json.load()
  • JSONPath
    • JSONPath与Xpath区别
    • XML
  • 数据提取总结
    • HTML、XML
    • JSON
    • XML
    • 其他
  • 总结

前言

简述
结构化的数据是最好处理的,一般都是类似JSON格式的字符串,直接解析JSON数据,提取JSON的关键字段即可。


话不多说,开始学习

JSON

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式;适用于进行数据交互的场景,比如网站前台与后台之间的数据交互

Json模块提供了四个功能:dumps、dump、loads、load,用于字符串 和 python数据类型间进行转换

Python操作json的标准api库参考

在线JSON格式化代码

1. json.loads()

实现:json字符串 转化 python的类型,返回一个python的类型

从json到python的类型转化对照如下:

import json
a="[1,2,3,4]"
b='{"k1":1,"k2":2}'#当字符串为字典时{}外面必须是''单引号{}里面必须是""双引号
print json.loads(a)
[1, 2, 3, 4]
print json.loads(b)
{'k2': 2, 'k1': 1}

案例

import urllib2
import json
response = urllib2.urlopen(r'http://api.douban.com/v2/book/isbn/9787218087351')
hjson = json.loads(response.read())
print hjson.keys()
print hjson['rating']
print hjson['images']['large']
print hjson['summary']

2. json.dumps()

实现python类型转化为json字符串,返回一个str对象

从python原始类型向json类型的转化对照如下:

import json
a = [1,2,3,4]
b ={"k1":1,"k2":2}
c = (1,2,3,4)
json.dumps(a)
'[1, 2, 3, 4]'
json.dumps(b)
'{"k2": 2, "k1": 1}'
json.dumps(c)
'[1, 2, 3, 4]'

json.dumps 中的ensure_ascii 参数引起的中文编码问题

如果Python Dict字典含有中文,json.dumps 序列化时对中文默认使用的ascii编码

import chardet
import json
b = {"name":"中国"}
json.dumps(b)
'{"name": "\\u4e2d\\u56fd"}'
print json.dumps(b)
{"name": "\u4e2d\u56fd"}
chardet.detect(json.dumps(b))
{'confidence': 1.0, 'encoding': 'ascii'}

‘中国’ 是ascii 字符码,而不是真正的中文。

想输出真正的中文需要指定ensure_ascii=False

json.dumps(b,ensure_ascii=False)
'{"name": "\xe6\x88\x91"}'
print json.dumps(b,ensure_ascii=False)
{"name": "我"}
chardet.detect(json.dumps(b,ensure_ascii=False))
{'confidence': 0.7525, 'encoding': 'utf-8'}
  • 初步使用

首先我们利用lxml来解析 HTML 代码,先来一个小例子来感受一下它的基本用法。

使用 lxml 的 etree 库,然后利用 etree.HTML 初始化,然后我们将其打印出来。

from lxml import etree
text = '''
<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"><span class="bold">third item</span></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></ul>
</div>
'''
#Parses an HTML document from a string
html = etree.HTML(text)
#Serialize an element to an encoded string representation of its XML tree
result = etree.tostring(html)
print result

所以输出结果是这样的

<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"><span class="bold">third item</span></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>

3. json.dump()

把Python类型 以 字符串的形式 写到文件中

import json
a = [1,2,3,4]
json.dump(a,open("digital.json","w"))
b = {"name":"我"}
json.dump(b,open("name.json","w"),ensure_ascii=False)
json.dump(b,open("name2.json","w"),ensure_ascii=True)

4. json.load()

读取 文件中json形式的字符串元素 转化成python类型

# -*- coding: utf-8 -*-
import json
number = json.load(open("digital.json"))
print number
b = json.load(open("name.json"))
print b
b.keys()
print b['name']

JSONPath

JSON 信息抽取类库,从JSON文档中抽取指定信息的工具

JSONPath与Xpath区别

JsonPath 对于 JSON 来说,相当于 XPATH 对于XML。

下载地址:

https://pypi.python.org/pypi/jsonpath/

安装方法:

下载jsonpath,解压之后执行’python setup.py install

参考文档

XPath JSONPath Result
/store/book/author $.store.book[].author the authors of all books in the store
//author $..author all authors
/store/ $.store. all things in store, which are some books and a red bicycle.
/store//price $.store..price the price of everything in the store.
//book[3] $..book[2] the third book
//book[last()] $..book[(@.length-1)]$..book[-1:] the last book in order.
//book[position()<3] $..book[0,1]$..book[:2] the first two books
//book[isbn] $..book[?(@.isbn)] filter all books with isbn number
//book[price<10] $..book[?(@.price<10)] filter all books cheapier than 10
// $..* all Elements in XML document. All members of JSON structure.

案例

以 http://www.lagou.com/lbs/getAllCitySearchLabels.json 为例,获取所有城市

import jsonpath
import urllib2
import chardet
url ='http://www.lagou.com/lbs/getAllCitySearchLabels.json'
request =urllib2.Request(url)
response = urllib2.urlopen(request)
print response.code
resHtml = response.read()
##detect charset
print chardet.detect(resHtml)
jsonobj = json.loads(resHtml)
citylist = jsonpath.jsonpath(jsonobj,'$..name')
print citylist
print type(citylist)
fp = open('city.json','w')
content = json.dumps(citylist,ensure_ascii=False)
print content
fp.write(content.encode('utf-8'))
fp.close()

XML

xmltodict模块让使用XML感觉跟操作JSON一样

Python操作XML的第三方库参考:

https://github.com/martinblech/xmltodict

模块安装:

pip install xmltodict
import xmltodict
bookdict = xmltodict.parse("""<bookstore><book><title lang="eng">Harry Potter</title><price>29.99</price></book><book><title lang="eng">Learning XML</title><price>39.95</price></book></bookstore>""")
print bookdict.keys()
[u'bookstore']
print json.dumps(bookdict,indent=4)

输出结果:

{"bookstore": {"book": [{"title": {"@lang": "eng", "#text": "Harry Potter"}, "price": "29.99"}, {"title": {"@lang": "eng", "#text": "Learning XML"}, "price": "39.95"}]}
}

数据提取总结

HTML、XML

XPath
CSS选择器
正则表达式

JSON

JSONPath
转化成Python类型进行操作(json类)

XML

  转化成Python类型(xmltodict)XPathCSS选择器正则表达式

其他

如:js、文本、电话号码、邮箱地址 等

  正则表达式


总结

Python爬虫基础入门系列(7) 就到这啦,阿星祝你早日修炼成为爬虫大佬!当然,如果你准备系统地学爬虫及更多Python编程技术,可戳我文末的名片,Free领取最新Python爬虫资料/免费咨询/学习规划~

戳我名片 · 领取福利

结构化数据丨Python爬虫基础入门系列(7)相关推荐

  1. Urllib2库丨Python爬虫基础入门系列(12)

    提示:文末有福利!最新Python爬虫资料/学习指南>>戳我直达 文章目录 前言 Urllib2库 学习目的 urlopen GET请求方式 利用urllib2.Request类,添加He ...

  2. 用爬虫抓取动态加载数据丨Python爬虫实战系列(6)

    提示:最新Python爬虫资料/代码练习>>戳我直达 前言 抓取动态加载数据 话不多说,开练! 爬虫抓取动态加载数据 确定网站类型 首先要明确网站的类型,即是动态还是静态.检查方法:右键查 ...

  3. 用爬虫收集网站公开数据丨Python爬虫实战系列(5)

    提示:最新Python爬虫资料/代码练习>>戳我直达 文章目录 前言 用爬虫收集公开数据 编写程序流程分析 确定Xpath表达式 1) 确定基准表达式 2) 确定抓取信息的表达式 3) 提 ...

  4. python爬虫基础入门理论篇(下)

    网络基础 2.1.网络协议 2.1.1什么是协议? 协议可以理解为"规则",是数据传输和数据的解释规则,下图是简单图解 2.1.2.OSI七层参考模型 物理层:可以理解为我们的网线 ...

  5. Python爬虫基础入门(二)——列表

    知识 1.列表的定义与访问 列表的格式 nameList = ['xiaozhang','xiaowang','xiaohua'] 比起C语言的数组强大的地方在于Python列表中的元素可以是不同类型 ...

  6. Python爬虫基础入门

    爬取的网址:https://www.23hh.com/book/0/189/ 需求:获取小说的章节目录及其对应的章节内容 需要的库:requests.BeautifulSoup和re.利用reques ...

  7. 如何自学python爬虫-怎样入门学习Python爬虫?

    怎样入门学习Python爬虫? 1.掌握Python编程能基础 想要学习爬虫,首先要充分掌握Python编程技术相关的基础知识.爬虫其实就是遵循一定的规则获取数据的过程,所以在学习Python知识的过 ...

  8. python爬虫工程师 成长之路六(二) 非结构化数据之lxml库

    文章目录 lxml库 介绍 lxml库 使用 最后 lxml库 介绍 lxml是一个使用python编写的库,处理XML非常方便,另外还支持XPath,(上篇博客的XPath派上用处了XPath 基础 ...

  9. Python爬虫(七)_非结构化数据与结构化数据

    页面解析与数据提取 实际上爬虫一共就四个主要步骤: 定(要知道你准备在哪个范围或者网站去搜索) 爬(将所有的网站的内容全部爬下来) 取(分析数据,去掉对我们没用处的数据) 存(按照我们想要的方式存储和 ...

最新文章

  1. [翻译] ASP.NET内幕 - IIS处理模型
  2. ​如何设计一个安全可靠的 API 接口?
  3. 为何信标无线充电总是烧板子?
  4. UNIX中的Select函数
  5. 转【快速把web项目部署到weblogic上】
  6. 性能测试三十九:Jprofiler分析CPU过高和响应时间长的问题
  7. 【转】Android 带checkbox的listView 实现多选,全选,反选 -- 不错
  8. 数据库-MySQL-结果集-ASORDER BY
  9. 前排强势围观|云端落地AI,如此超级干货有哪些?
  10. SQL中JOIN和UNION区别及用法
  11. Excel表格常用功能快捷键
  12. uniapp本地存储
  13. 简单Python爬取链接二手房信息
  14. vue组件 组件的继承extend
  15. [已解决]smallbin double linked list
  16. 看小伙是怎么发现CSDN前10大佬之间的关系的
  17. 三国杀 中的概率计算 几何分布的期望和方差分析
  18. android 恢复出厂设置 代码,android恢复出厂设置以及系统升级流程
  19. Python之异常处理(异常处理机制,抛出异常,自定义异常)
  20. dom4j生成xml节点内容换行

热门文章

  1. 【招银网络科技java面试题目面试经验】-看准网
  2. 【良心】C语言零基础学习,C语言初学者入门基础知识讲解
  3. QT中 :-1: error: Failed to resolve include /moc_predefs.h“ for moc file
  4. 小Y看浮屠世界-纸杯世界:含有荧光增白剂的爆米花桶只是冰山一角
  5. ncr管理系统_【拆解】米家骑记电助力折叠自行车,看看里面的电子方案
  6. Python每日一练------搬砖
  7. 蘑菇云matlab程序,貂蝉搞怪去衣福利图片欣赏(图文)
  8. 3升杯子5升杯子倒出4升水
  9. 中断深入-->休眠唤醒(通用)
  10. 数据库的用户信息表设计