最近沉迷于python爬虫,学习的是崔庆才老师的这本书 python3网络爬虫开发实战,书是好书,只不过因为技术更新,原书的一些代码已经不能使用,特写此篇来记录自己的一些爬坑经历。
爬取结果:
如果你爬取的套图只有一张的话,很可能是因为你访问的是视频,而不是图片,例如:
注意点一:
进入网站,进入开发者模式,我们可以看到有aid, app_name,offset, format, keyword, autoload, count, en_qc, cur_tab, from, pd, timestamp, _signature,我们在传递参数时,可以不用传递后面两个键值对:timestamp(发送请求时的时间戳)和_signature(数字签名),有关数字签名的讲解可以看看这篇博客:阮一峰的网络日志:数字签名是什么?
注意点二:
套图链接是在 data/1/ image_list 中:
而不是书本上的 image_detail
注意点三:
Request URL里的keyworld的值是:%E8%A1%97%E6%8B%8D,但是经过验证,当我传入的keyworld值是%E8%A1%97%E6%8B%8D时,爬取的图片如下:不知道是些啥
当我们把keywrold改成网页 URL中的keyworld时就可以爬取到图片了:
注意点四:
如果使用windows的朋友要注意了,作者用的操作系统是MAC,路径的分隔符只要 / 即可,而windows记得要用 \ 转义!即: ‘C:\\Users\\xx\\images’
注意:下面的代码中,图片保存的位置要自己重新确定!!
get_page(offset):
def get_page(offset):
params = {
'aid': '24',
'app_name': 'web_search',
'offset': offset,
'format': 'json',
'keyword': '街拍',
'autoload': 'true',
'count': '20',
'en_qc': '1',
'cur_tab': '1',
'from': 'search_tab',
'pd': 'synthesis'
}
url = 'https://www.toutiao.com/api/search/content/?'+urlencode(params)
try:
response = requests.get(url)
if response.status_code == 200:
return response.json()
except requests.ConnectionError:
print("请求出错!!")
parse_image(json):
为防止imaegs为空,出现 TypeError:‘NoneType’ object is not iterable,我们要对得到的图片链接进行判断
def get_image(json):
if json.get('data'):
for item in json.get('data'):
title = item.get('title')
images = item.get('image_list')
# print(title)
if images: # 防止imaegs为空,TypeError:‘NoneType’ object is not iterable
for image in images:
yield{
'image': image.get('url'),
'title': title
}
else:
print('没有图片!')
save_image(item):
def save_image(item):
dir_name = item['title'][:8]
dir_path = 'C:\\xxx\\xx\\'+dir_name # 保存路径自己决定
if not os.path.exists(dir_path):
os.mkdir(dir_path)
try:
response = requests.get(item.get('image'))
if response.status_code == 200:
file_path = dir_path+'\\{0}.{1}'.format(md5(response.content).hexdigest(), 'jpg')
# md5摘要算法(哈希算法),通过摘要算法得到一个长度固定的数据块。
# md5() 获取一个md5加密算法对象
# hexdigest() 获取加密后的16进制字符串。
if not os.path.exists(file_path):
# print("这里会不会执行啊???")
with open(file_path, 'wb') as f:
f.write(response.content)
else:
print('Already Downloaded')
except requests.ConnectionError:
print("保存图片失败!")
源代码:
import requests
import os
from urllib.parse import urlencode
from hashlib import md5
def get_page(offset):
params = {
'aid': '24',
'app_name': 'web_search',
'offset': offset,
'format': 'json',
'keyword': '街拍',
'autoload': 'true',
'count': '20',
'en_qc': '1',
'cur_tab': '1',
'from': 'search_tab',
'pd': 'synthesis'
}
url = 'https://www.toutiao.com/api/search/content/?'+urlencode(params)
try:
response = requests.get(url)
if response.status_code == 200:
return response.json()
except requests.ConnectionError:
print("请求出错!!")
def get_image(json):
if json.get('data'):
for item in json.get('data'):
title = item.get('title')
images = item.get('image_list')
# print(title)
if images: # * 防止imaegs为空,TypeError:‘NoneType’ object is not iterable
for image in images:
yield{
'image': image.get('url'),
'title': title
}
else:
print('没有图片!')
def save_image(item):
dir_name = item['title'][:8]
dir_path = 'C:\\xx\\xx\\'+dir_name
if not os.path.exists(dir_path):
os.mkdir(dir_path)
try:
response = requests.get(item.get('image'))
if response.status_code == 200:
file_path = dir_path+'\\{0}.{1}'.format(md5(response.content).hexdigest(), 'jpg')
print(file_path)
if not os.path.exists(file_path):
with open(file_path, 'wb') as f:
f.write(response.content)
else:
print('Already Downloaded')
except requests.ConnectionError:
print("保存图片失败!")
def main(offset):
json = get_page(offset)
for item in get_image(json):
save_image(item)
if __name__ == '__main__':
for offset in [x*20 for x in range(0, 2)]:
print('第{}个图片集'.format(offset+1))
main(offset)