Python爬取动态网页中图片的完整实例

 更新时间:2021年03月09日 09:11:57   作者:割韭菜的喵酱  
这篇文章主要给大家介绍了关于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()

效果

总结

到此这篇关于Python爬取动态网页中图片的文章就介绍到这了,更多相关Python爬取动态网页图片内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • python使用SimpleXMLRPCServer实现简单的rpc过程

    python使用SimpleXMLRPCServer实现简单的rpc过程

    这篇文章主要介绍了python使用SimpleXMLRPCServer实现简单的rpc过程,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-06-06
  • pycharm中keras导入报错无法自动补全cannot find reference分析

    pycharm中keras导入报错无法自动补全cannot find reference分析

    这篇文章主要介绍了pycharm中keras导入报错无法自动补全cannot find reference分析,文章围绕主题展开分析,需要的小伙伴可以参考一下
    2022-07-07
  • python数据可视化之日期折线图画法

    python数据可视化之日期折线图画法

    这篇文章主要为大家详细介绍了python数据可视化之日期折线图画法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-04-04
  • Python如何使用paramiko模块连接linux

    Python如何使用paramiko模块连接linux

    这篇文章主要介绍了Python如何使用paramiko模块连接linux,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-03-03
  • pytorch绘制并显示loss曲线和acc曲线,LeNet5识别图像准确率

    pytorch绘制并显示loss曲线和acc曲线,LeNet5识别图像准确率

    今天小编就为大家分享一篇pytorch绘制并显示loss曲线和acc曲线,LeNet5识别图像准确率,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-01-01
  • python实现图像拼接功能

    python实现图像拼接功能

    这篇文章主要为大家详细介绍了python实现图像拼接功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-03-03
  • python自动截取需要区域,进行图像识别的方法

    python自动截取需要区域,进行图像识别的方法

    今天小编就为大家分享一篇python自动截取需要区域,进行图像识别的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-05-05
  • Python 3中print函数的使用方法总结

    Python 3中print函数的使用方法总结

    这篇文章主要给大家总结介绍了关于Python 3中print函数的使用方法,python3中的print函数和之前版本的用法相差很多,本文通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面来一起看看吧。
    2017-08-08
  • pandas df.sample()的使用

    pandas df.sample()的使用

    本文主要介绍了pandas df.sample()的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-08-08
  • Python中的线程同步的常用方法总结

    Python中的线程同步的常用方法总结

    在Python多线程编程中,我们常常需要处理多个线程同时访问共享数据的情况,为了防止数据在多线程之间出现冲突,我们需要对线程进行同步。本文将详细介绍Python中的线程同步的几种常用方法,需要的朋友可以参考下
    2023-06-06

最新评论