Python爬取 * 页中图片的完整实例
作者:割韭菜的喵酱 发布时间:2023-11-12 20:29:27
标签:python,爬虫,网页
* 页爬取是爬虫学习中的一个难点。本文将以知名插画网站pixiv为例,简要介绍 * 页爬取的方法。
写在前面
本代码的功能是输入画师的pixiv id,下载画师的所有插画。由于本人水平所限,所以代码不能实现自动登录pixiv,需要在运行时手动输入网站的cookie值。
重点:请求头的构造,json文件网址的查找,json中信息的提取
分析
创建文件夹
根据画师的id创建文件夹(相关路径需要自行调整)。
def makefolder(id): # 根据画师的id创建对应的文件夹
try:
folder = os.path.join('E:\pixivimages', id)
os.mkdir(folder)
return folder
except(FileExistsError):
print('the folder exists!')
exit()
获取作者所有图片的id
访问url:https://pixiv.net/ajax/user/画师id/profile/all(这个json可以在画师主页url:https://www.pixiv.net/users/画师id 的开发者面板中找到,如图:)
json内容:
将json文档转化为python的字典,提取对应元素即可获取所有的插画id。
def getAuthorAllPicID(id, cookie): # 获取画师所有图片的id
url = 'https://pixiv.net/ajax/user/' + id + '/profile/all' # 访问存有画师所有作品
headers = {
'User-Agent': user_agent,
'Cookie': cookie,
'Referer': 'https://www.pixiv.net/artworks/'
# referer不能缺少,否则会403
}
res = requests.get(url, headers=headers, proxies=proxies)
if res.status_code == 200:
resdict = json.loads(res.content)['body']['illusts'] # 将json转化为python的字典后提取元素
return [key for key in resdict] # 返回所有图片id
else:
print("Can not get the author's picture ids!")
exit()
获取图片的真实url并下载
访问url:https://www.pixiv.net/ajax/illust/图片id?lang=zh,可以看到储存有图片真实地址的json:(这个json可以在图片url:https://www.pixiv.net/artworks/图片id 的开发者面板中找到)
用同样的方法提取json中有用的元素:
def getPictures(folder, IDlist, cookie): # 访问图片储存的真实网址
for picid in IDlist:
url1 = 'https://www.pixiv.net/artworks/{}'.format(picid) # 注意这里referer必不可少,否则会报403
headers = {
'User-Agent': user_agent,
'Cookie': cookie,
'Referer': url1
}
url = 'https://www.pixiv.net/ajax/illust/' + str(picid) + '?lang = zh' #访问储存图片网址的json
res = requests.get(url, headers=headers, proxies=proxies)
if res.status_code == 200:
data = json.loads(res.content)
picurl = data['body']['urls']['original'] # 在字典中找到储存图片的路径与标题
title = data['body']['title']
title = changeTitle(title) # 调整标题
print(title)
print(picurl)
download(folder, picurl, title, headers)
else:
print("Can not get the urls of the pictures!")
exit()
def changeTitle(title): # 为了防止
global i
title = re.sub('[*:]', "", title) # 如果图片中有下列符号,可能会导致图片无法成功下载
# 注意可能还会有许多不能用于文件命名的符号,如果找到对应符号要将其添加到正则表达式中
if title == '無題': # pixiv中有许多名为'無題'(日文)的图片,需要对它们加以区分以防止覆盖
title = title + str(i)
i = i + 1
return title
def download(folder, picurl, title, headers): # 将图片下载到文件夹中
img = requests.get(picurl, headers=headers, proxies=proxies)
if img.status_code == 200:
with open(folder + '\\' + title + '.jpg', 'wb') as file: # 保存图片
print("downloading:" + title)
file.write(img.content)
else:
print("download pictures error!")
完整代码
import requests
from fake_useragent import UserAgent
import json
import re
import os
global i
i = 0
ua = UserAgent() # 生成假的浏览器请求头,防止被封ip
user_agent = ua.random # 随机选择一个浏览器
proxies = {'http': 'http://127.0.0.1:51837', 'https': 'http://127.0.0.1:51837'} # 代理,根据自己实际情况调整,注意在请求时一定不要忘记代理!!
def makefolder(id): # 根据画师的id创建对应的文件夹
try:
folder = os.path.join('E:\pixivimages', id)
os.mkdir(folder)
return folder
except(FileExistsError):
print('the folder exists!')
exit()
def getAuthorAllPicID(id, cookie): # 获取画师所有图片的id
url = 'https://pixiv.net/ajax/user/' + id + '/profile/all' # 访问存有画师所有作品
headers = {
'User-Agent': user_agent,
'Cookie': cookie,
'Referer': 'https://www.pixiv.net/artworks/'
}
res = requests.get(url, headers=headers, proxies=proxies)
if res.status_code == 200:
resdict = json.loads(res.content)['body']['illusts'] # 将json转化为python的字典后提取元素
return [key for key in resdict] # 返回所有图片id
else:
print("Can not get the author's picture ids!")
exit()
def getPictures(folder, IDlist, cookie): # 访问图片储存的真实网址
for picid in IDlist:
url1 = 'https://www.pixiv.net/artworks/{}'.format(picid) # 注意这里referer必不可少,否则会报403
headers = {
'User-Agent': user_agent,
'Cookie': cookie,
'Referer': url1
}
url = 'https://www.pixiv.net/ajax/illust/' + str(picid) + '?lang = zh' #访问储存图片网址的json
res = requests.get(url, headers=headers, proxies=proxies)
if res.status_code == 200:
data = json.loads(res.content)
picurl = data['body']['urls']['original'] # 在字典中找到储存图片的路径与标题
title = data['body']['title']
title = changeTitle(title) # 调整标题
print(title)
print(picurl)
download(folder, picurl, title, headers)
else:
print("Can not get the urls of the pictures!")
exit()
def changeTitle(title): # 为了防止
global i
title = re.sub('[*:]', "", title) # 如果图片中有下列符号,可能会导致图片无法成功下载
# 注意可能还会有许多不能用于文件命名的符号,如果找到对应符号要将其添加到正则表达式中
if title == '無題': # pixiv中有许多名为'無題'(日文)的图片,需要对它们加以区分以防止覆盖
title = title + str(i)
i = i + 1
return title
def download(folder, picurl, title, headers): # 将图片下载到文件夹中
img = requests.get(picurl, headers=headers, proxies=proxies)
if img.status_code == 200:
with open(folder + '\\' + title + '.jpg', 'wb') as file: # 保存图片
print("downloading:" + title)
file.write(img.content)
else:
print("download pictures error!")
def main():
global i
id = input('input the id of the artist:')
cookie = input('input your cookie:') # 半自动爬虫,需要自己事先登录pixiv以获取cookie
folder = makefolder(id)
IDlist = getAuthorAllPicID(id, cookie)
getPictures(folder, IDlist, cookie)
if __name__ == '__main__':
main()
效果
总结
来源:https://blog.csdn.net/m0_51908955/article/details/114459226


猜你喜欢
- 1、什么是水仙花数?水仙花数(Narcissistic number)也被称为超完全数字不变数(pluperfect digit
- Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。基本语法是通过 {} 和 :
- 实现效果UI组件依然是使用 Quasar Framework。先来看一下效果:加减.gifinput type="number&q
- 数据驱动模式的测试好处相比普通模式的测试就显而易见了吧!使用数据驱动的模式,可以根据业务分解测试数据,只需定义变量,使用外部或者自定义的数据
- 找了 很多 关于表格分页 点击事件 请求, table.render 并不支持监听点击事件,所以我就把 table.render 和 lay
- 1. 使用 length 属性追加元素使用length属性,可以在数组末尾后面添加一个元素var arr = [1, 2, 3, 4, 5]
- 这篇文章主要是想说,“引用只能指向具体对象而不能指向引用”//创建变量testArray 并引用数组 ["1&
- 本文实例讲述了vue.js使用v-if实现显示与隐藏功能。分享给大家供大家参考,具体如下:<!doctype html><
- 写在前面最近在使用Mockjs作为项目里面mock数据的工具,发现mockjs做的拦截部分是自己实现摸拟了一个XMLHttpRequest的
- 这篇文章主要介绍了原生Java操作mysql数据库过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要
- 前言:如果使用进到的日志文件方法:logging.FileHandler,会导致日志信息全部存放在一个日志文件中,不利于后面对日志文件的使用
- 函数表达式和函数声明在ECMAScript中,创建函数的最常用的两个方法是函数表达式和函数声明,两者期间的区别是有点晕,因为ECMA规范只明
- 概述用爬虫时,大部分网站都有一定的反爬措施,有些网站会限制每个 IP 的访问速度或访问次数,超出了它的限制你的 IP 就会被封掉。对于访问速
- 在 Go 中,数组和切片的功能其实是类似的,都是用来存储一种类型元素的集合。数组是固定长度的,而切片的长度是可以调整的数组(array)我们
- 如下所示:a, b, c = 1, 2, 3 # 1.常规 if a>b: &nbs
- 最近在做一个站点时,需要生成静态页面,但是生成的静态页面中有些内容是需要动态获取的,怎不能每天生成一下吧。。 最后上网查了一下,再加上个要总
- 多标签分类器多标签分类任务与多分类任务有所不同,多分类任务是将一个实例分到某个类别中,多标签分类任务是将某个实例分到多个类别中。多标签分类任
- 这篇文章主要介绍了基于python3抓取pinpoint应用信息入库,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习
- <% '#######以下是一个类文件,下面的注解是调用类的方法####################
- 业务场景:前后端分离需要对接数据接口。接口测试是在postman做的,今天才开始和前端对接,由于这是我第一次做后端接口开发(第一次嘛,问题比