通过python爬虫下载wallhaven壁纸
2019-08-11 本文已影响3人
modao233
仅供学习
Awesome Wallpapers - wallhaven.cc
- 官网:https://alpha.wallhaven.cc/
- 主题:创意、摄影、人物、动漫、绘画、视觉
- 分辨率:~4K
- 说明:图片丰富,质量很高,分为通用、动漫、人物三大类,可以按屏幕比例和分辨率检索。
首先,打开网站,https://wallhaven.cc/,那我选择了toplist
跳转后进入:https://wallhaven.cc/toplist,这时候注意地址栏的URL,然后滚动鼠标中键向下浏览,会发现地址栏有变化,例如:https://wallhaven.cc/toplist?page=2
仔细看page与page之间是有分割线的
图片.png
发现总共有183的page,
然后我们右键查看页面源代码,我在Firefox看源代码没有缩进,观察起来很累
所以先用BeautifulSoup简单处理下。可参考代码:
import os
import requests
from bs4 import BeautifulSoup
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36'
}
page = requests.get('https://wallhaven.cc/toplist?page=100', headers=headers)
bsObj = BeautifulSoup(page.text, "html.parser")
path = './middle.txt'
with open(path,'wb') as f:
f.write(bsObj.prettify().encode())
然后我们在page.txt里** 搜索jpg **
图片.png
可以发现图片在标签树的位置,
<img alt="loading" class="lazyload" data-src="https://th.wallhaven.cc/small/wy/wydem6.jpg" src=""/>
其中,data-src就是壁纸的缩略图的地址。
图片.png接着我们发现,在图片缩略图所在代码下面还有一个preview
preview后面也有一个地址
复制到浏览器打开,就进入了图片的放大预览页面,同样查看该源代码。
搜索jpg,会发现有一个名字和之前壁纸缩略图地址很像的地址,这可能就是我们要的壁纸的地址了
<img id="wallpaper" src="https://w.wallhaven.cc/full/wy/wallhaven-wydem6.jpg"
复制地址到浏览器打开,发现就是这个了。
https://th.wallhaven.cc/small/wy/wydem6.jpg
https://w.wallhaven.cc/full/wy/wallhaven-wydem6.jpg
通过对比,我们就可以得到转化规则了。
接下来是全部代码。
import time
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
import requests
import threading
import os
#设置请求头,随机的
headers= {'User-Agent':str(UserAgent().random)}
#通过生成器返回页面地址
def get_page_url():
for i in range(1, 3):
yield 'https://wallhaven.cc/toplist?page={}'.format(i)
#发送请求,得到页面
def get_html(url):
try:
r = requests.get(url, headers=headers)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r
except Exception as e:
print(e)
#存放所有页面Page的壁纸缩略图地址
images = []
#提取每一个page的壁纸缩略图地址,存放进images
def get_href(url):
res = get_html(url).text
bsObj = BeautifulSoup(res, "html.parser")
r = bsObj.select('div#thumbs section.thumb-listing-page ul li figure img')
for i in r:
if i['data-src'] not in images:
images.append(i['data-src'])
else:
continue
#下载模块
def download_pics(url, name):
r = get_html(url)
path = './' + str(name)
with open(path,'wb') as f:
f.write(r.content)
# #下载完了,解锁
# thread_lock.release()
#设置一个简单的计时器
start = time.time()
#转到存放下载文件的目录
os.chdir('D:/python-download/wallhaven/')
# #设置最大线程 开启10个线程就锁住
# thread_lock = threading.BoundedSemaphore(value=10)
#通过循环获取生成器传出来的值
for i in get_page_url():
get_href(i)
n = 0
for image in images[:10]:
#根据转化规则获得真实高清壁纸地址
author = image.split('/')[-2]
name = image.split('/')[-1]
image = 'https://w.wallhaven.cc/full/' + author + '/wallhaven-' + name
n += 1
print('正在下载第{}张图片'.format(n))
download_pics(image, name)
# # 上锁
# thread_lock.acquire()
# 下载 这个方法丢进线程池
# t = threading.Thread(target=download_pics, args=(image, name))
# t.start()
# #time.sleep(0.3)
end = time.time()
spend = end - start
print('共花费{:.2f}秒'.format(spend))