Python爬取动态网站(进阶版)

这是一个Python爬虫程序,通过多线程实现从Pixiv网站批量下载指定画师的作品。程序首先生成随机User-Agent以避免被封IP,然后使用代理进行网络请求。用户输入画师ID和Cookie,程序会为每个画师创建单独的文件夹,获取其所有图片ID,并下载原始尺寸的图片。同时,程序还对图片标题进行了处理,确保文件名的合法性。
摘要由CSDN通过智能技术生成

该代码是https://blog.csdn.net/m0_51908955/article/details/114459226的进阶版,引入多线程爬虫,一次可爬五个id。

代码

import requests
from fake_useragent import UserAgent
import threading
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'} # 代理,根据自己实际情况调整,注意在请求时一定不要忘记代理!!

class myThread(threading.Thread):
    def __init__(self, id, cookie):
        threading.Thread.__init__(self)
        self.id = id
        self.cookie = cookie
    def run(self):
        print("Starting " + self.id)
        main(self.id, self.cookie)
        print("Exiting " + self.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()


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(id,cookie):
	global i
	folder = makefolder(id)
	IDlist = getAuthorAllPicID(id, cookie)
	getPictures(folder, IDlist, cookie)


if __name__ == '__main__':
	idlist=[]
	for i in range(4):
		idlist.append(input('input id %d:'%i))
	cookie = input('input your cookie:') # 半自动爬虫,需要自己事先登录pixiv以获取cookie
	threads=[]
	for i in range(0,4):
		# 创建4个新线程
		thread = myThread(id=idlist[i], cookie=cookie)
		# 开启新线程
		thread.start()
		# 添加新线程到线程列表
		threads.append(thread)
	# 等待所有线程完成
	for thread in threads:
		thread.join()
	print("Exiting Main Thread")
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值