前言
1、使用python自动从zol下载壁纸,比较简单,高手自动忽略。
2、没进行翻页的处理,只单纯down了一个页面的图片而已。
3、整体逻辑,解析缩略图页面,自动请求高清url并下载到本地。
源码
import requests, bs4, re
# 发起请求
def myUrlGet(url):
try:
res = requests.get(url)
res.raise_for_status()
return res
except Exception as exc:
print('get %s url failed: %s' % (url, exc))
return
# 保存图片
def saveImgFile(filename, url):
imgres = myUrlGet(url)
if imgres != "" and len(imgres.content) > 0:
try:
imgFile = open(filename, 'wb')
except Exception as exc:
print('can not open file: %s' % (exc))
return
imgFile.write(imgres.content)
# 获取壁纸原始地址
def downZolImg(imgname, imgurl):
imgres = myUrlGet(imgurl)
if imgres != None:
soup = bs4.BeautifulSoup(imgres.text)
imgorig = soup.select('#bigImg')
if len(imgorig) > 0:
saveImgFile('img/' + imgname, imgorig[0].attrs['src'])
# 主处理逻辑
if __name__ == '__main__':
zolurl = 'http://desk.zol.com.cn/'
zolres = myUrlGet(zolurl + 'nb/')
if zolres != None:
zolsoup = bs4.BeautifulSoup(zolres.text)
photoList = zolsoup.select('.photo-list-padding')
photoNameRegex = re.compile(r'([^/]+)\.html')
for photo in photoList:
photourl = photo.contents[0].attrs['href']
photoName = photoNameRegex.search(photourl).group(1) + '.jpg'
print(photoName, zolurl + photourl)
downZolImg(photoName, zolurl + photourl)