前言
突然发现,在学习Python爬虫的时候重复走了一些弯路,比如信息提取这一块,对于很明显的json采用的居然是re,正则虽然强大,但是在遇到json数据后依旧使用正则去提取是一件很不理智的一件事,而在前几篇喜马拉雅有声小说爬取时采用的便是re,现在看来实在是变扭,所以赶紧重新写一遍也提醒广大起步学爬虫的大兄弟们: json数据不要再使用正则了!,当然也可能只是我个人菜到只会正则表达式
通俗易懂,像是这样
pprint一下就是:这样的键值对
是不是很好看!写代码更能使代码更加整洁、舒适
体感Json
(以下为从前上课笔记,如有雷同,纯属一个老师的巧合,但是代码是自己写的!)
- json作为键值对的一种特殊例子,ta可以是
Json值可以是 | Python类型 |
---|---|
数字(整数或浮点数) | int、float |
字符串(在双引号中) | str |
逻辑值(true或false) | True、False |
数组(在中括号中[ ]) | list[ ] |
对象(在大括号中{ }) | dict{ } |
null | None |
- 实例:爬取百度图片
提示:如果你没有看见,是因为页面为动态加载,你需要下拉网页加载出新的数据
当我们利用爬虫得到这一长串的数据后,便可以利用JSON来提取数据,看了代码之后你就会明白我的用意
result = requests.get(url, params=params, headers=headers).json()
data = result['data']
得到的就是:
再利用循环去提取里面的目标元素是值
for imageURL in data:
imageURL = imageURL['thumbURL']
# print(imageURL)
img = requests.get(imageURL)
完整的代码块:
import requests
from pprint import pprint
import random
# url = 'https://image.baidu.com/search/acjson?tn=resultjson_com&logid=9379898655806102405&ipn=rj&ct=201326592&is=&fp=result&queryWord=%E5%AE%AB%E5%B4%8E%E9%AA%8F&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=0&hd=&latest=©right=&word=%E5%AE%AB%E5%B4%8E%E9%AA%8F&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&fr=&expermode=&force=&pn=30&rn=30&gsm=1e&1616136244745='
url = 'https://image.baidu.com/search/acjson'
params = {
'tn': 'resultjson_com' ,
'logid': '9379898655806102405',
'ipn': 'rj',
'ct': '201326592',
'is': '',
'fp': 'result',
'queryWord': '进击的巨人',
'cl': '2',
'lm': '-1',
'ie': 'utf-8',
'oe': 'utf-8',
'adpicid': '',
'st': '-1',
'z': '',
'ic': '0',
'hd': '',
'latest': '',
'copyright': '',
'word': '进击的巨人',
's': '',
'se': '',
'tab': '',
'width': '',
'height': '',
'face': '0',
'istype': '2',
'qc': '',
'nc': '1',
'fr': '',
'expermode': '',
'force': '',
'pn': '30',
'rn': '30',
'gsm': '1e',
'1616136244745': ''
}
headers = {
'Host': 'image.baidu.com',
'Referer': 'https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=index&fr=&hs=0&xthttps=111210&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E5%AE%AB%E5%B4%8E%E9%AA%8F',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36'
}
result = requests.get(url, params=params, headers=headers).json()
data = result['data']
for imageURL in data:
imageURL = imageURL['thumbURL']
# print(imageURL)
img = requests.get(imageURL)
with open(f'{random.randint(1,1000)}.png', 'wb') as f:
f.write(img.content)
print('成功下载')
当然除了requests内置的json函数外, Python也提供了独立的JSON模块,ta的 目的就是将Python对象编码成JSON字符串,将JSON字符串解码成Python对象…更多的JSON知识请搜索JSON解锁,在此就只是一次体验