Python3爬取Wallhaven.cc图片
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python3爬取Wallhaven.cc图片,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含3604字,纯文字阅读大概需要6分钟。
内容图文
https://wallhaven.cc/ 上有很多优秀壁纸图片,网站访问速度有点慢,还是抓下来看比较方便。
1、安装python3
2、pip安装requests、lxml
3、运行代码
# -*- coding: utf-8 -*- # wallhaven爬取 import os from urllib.parse import urlencode import time from requests import codes import random import requests from lxml import etree #定义创建文件路径函数,将下载的文件存储到该路径def CreatePath(filepath): ifnot os.path.exists(filepath): os.makedirs(filepath) #定义获取url函数,这里是通过urlencode方法把url的各个部分拼接起来的,拼接起来的url #像是这样的:https://wallhaven.cc/search?q=girls&categories=111&purity=110&sorting=toplist&order=desc def GetUrl(keyword,category): params = { ‘q‘: keyword, ‘categories‘: category, ‘purity‘: ‘110‘,#100\010\110‘sorting‘: ‘favorites‘, #relevance\random\date_added\views\favorites\toplist\toplist-beta‘topRange‘:‘1y‘, #1y\6M\3M\1w\3d\1d‘order‘:‘desc‘ } base_url=‘https://wallhaven.cc/search?‘ url=base_url + urlencode(params) print(url) return url #获取查找到的图片数def GetPictureNum(url): allpic=""try: html = requests.get(url) if codes.ok == html.status_code: selector = etree.HTML(html.text) pageInfo = selector.xpath(‘//header[@class="listing-header"]/h1[1]/text()‘)#提取出文本 string = str(pageInfo[0])#图片数是文本中的第一个 numlist = list(filter(str.isdigit,string)) #有些数字是这样的,11,123,所以需要整理。for item in numlist: allpic+=item totalPicNum=int(allpic) #把拼接起来的字符串进行整数化return totalPicNum except requests.ConnectionError: return None #获取图片链接def GetLinks(url,number): urls=url+‘&page=‘+str(number) try: html=requests.get(urls) selector=etree.HTML(html.text) PicLink=selector.xpath(‘//a[@class="preview"]/@href‘)#这里寻找图片的链接地址,以求得到图片编号except Exception as e: print(‘Error‘,e.args) return PicLink #下载函数 def Download(filepath,keyword,url,count,headers):#其中count是你要下载的图片数 #此函数用于图片下载。其中参数url是形如:https://wallhaven.cc/w/eyyoj8 的网址 #因为wallheaven上只有两种格式的图片,分别是png和jpg,所以设置两种最终地址HtmlJpg和HtmlPng,通过status_code来进行判断,状态码为200时请求成功。 string=url.replace(‘https://wallhaven.cc/w/‘,‘‘) #python3 replace#print(string) HtmlJpg=‘https://w.wallhaven.cc/full/‘+ string[0:2] +‘/wallhaven-‘ + string +‘.jpg‘ HtmlPng=‘https://w.wallhaven.cc/full/‘+ string[0:2] +‘/wallhaven-‘ + string +‘.png‘try: pic=requests.get(HtmlJpg,headers=headers) if codes.ok==pic.status_code: pic_path=filepath+‘wallhaven-‘+string+‘.jpg‘else: pic=requests.get(HtmlPng,headers=headers) if codes.ok==pic.status_code: pic_path=filepath+‘wallhaven-‘+string+‘.png‘else: print("Downloaded error:",string) return with open(pic_path,‘wb‘) as f: f.write(pic.content) f.close() print("Downloaded image:",string) time.sleep(random.uniform(0,3))#这里是让爬虫在下载完一张图片后休息一下,防被侦查到是爬虫从而引发反爬虫机制。except Exception as e: print(repr(e)) #主函数def main(): headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36",#请求头,这个可以通过查看你自己的浏览器得到。 } filepath = (‘/wallpaper/Pictures/‘)#存储路径。 keyword=input(‘请输入关键词:‘) category=input(‘请输入图片分类,共有三种,分别为Gneral,Anime,People三种 ,如果你想要只想选择Anime,就键入010,如果全选就键入111,以此类推:‘) CreatePath(filepath) #创建保存路径 url=GetUrl(keyword,category) #获取url PicNum=GetPictureNum(url)#总图片数 pageNum=int(PicNum/24+1) #求出总页面数print("We found:{} images.".format(PicNum)) j=1 Arr = input("请输入你想要爬的图片数,不能超过已找到的图片数:【若要设定其实页码用|分割,如:50|10(即从第10页开始,取50个)】").split(‘|‘) Num = int(Arr[0]) pageStart=0 if(len(Arr) == 2): pageStart = int(Arr[1]) for i in range(pageStart,pageNum): PicUrl=GetLinks(url,i+1) for item in PicUrl: #print(item) Download(filepath,keyword,item,j,headers) j+=1 if(j>Num):#如果你下载的图片够用了,那就直接退出循环,结束程序。returnif__name__ == ‘__main__‘: main()
参考地址:https://www.jianshu.com/p/90f734cb895d
原文:https://www.cnblogs.com/kuangxiangnice/p/12046059.html
内容总结
以上是互联网集市为您收集整理的Python3爬取Wallhaven.cc图片全部内容,希望文章能够帮你解决Python3爬取Wallhaven.cc图片所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。