用到的主要知识点:
requests.get 获取网页HTML
etree.HTML 使用lxml解析器解析网页
xpath 使用xpath获取网页标签信息、图片地址
request.urlretrieve 下载图片(注:该网站使用urlretrieve下载图片时,返回403错误。原因目前未知!)
改用 with as 下载图片:
with open('文件地址及名字', 'wb') as f:
f.write(res.content)
详细代码如下:
#!/user/bin env python
import requests
from lxml import etree
from urllib import request
import urllib
import time
headers ={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
}
def getUrlText(url):
respons = requests.get(url,headers=headers) # 获取网页信息
urlText = respons.text
html = etree.HTML(urlText) # 使用lxml解析网页
return html
def getWallUrl(url):
hrefUrl = getUrlText(url)
section = hrefUrl.xpath('//section[@class="thumb-listing-page"]')[0] # 获取section标签
hrefList = section.xpath('./ul//@href') # 获取首页图片对应链接地址
return hrefList
def getTime():
nowtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
return nowtime
def downWall(url,page):
'''
:param url: 网页地址
:param page: 下载页数
:return: 下载结束提醒
'''
m = 0
page += 1
for i in range(1,page):
hrefList = getWallUrl(url+str(i))
n = 0
print('\033[36;1m*********** 开始下载第{}页壁纸 ************\033[0m'.format(i))
for href in hrefList:
n += 1
imgUrl = getUrlText(href) # 获取壁纸链接网页信息并解析
imgSrc = imgUrl.xpath('//img[@id="wallpaper"]/@src')[0]
# strUl = etree.tostring(imgSrc, encoding='utf-8').decode('utf-8') # 对获取到ul解码
# print(strUl)
imgType = imgSrc[-4:] # 壁纸格式
print('{}:\033[31;1m开始下载第{}页第{}张壁纸\033[0m'.format(getTime(),i,n))
# request.urlretrieve(imgSrc, './wall/' + str(n) + imgType) #403错误
res = requests.get(imgSrc)
with open('./wall/'+str(i)+'_'+str(n)+imgType, 'wb') as f:
f.write(res.content)
print('{}:\033[31;1m第{}页第{}张壁纸下载完成\033[0m'.format(getTime(),i,n))
m = m + n
return print('{}:\033[36;1m所有壁纸已下载完成,一共{}页{}张。\033[0m'.format(getTime(),i,m))
if __name__ == '__main__':
page =int(input('\033[36;1m请输入你想下载的页数:\033[0m'))
print('\033[36;1m程序执行中,请稍等。。。即将下载。\033[0m')
downWall('https://wall***&page=',page)
运行结果:
手机扫一扫
移动阅读更方便
你可能感兴趣的文章