如何使用Python获取高清壁纸呢?下面我给大家分享一下,直接附上源代码;
注意:实际使用时需根据网页内容调整代码
1.将前20页壁纸加入到列表中如下:
from urllib import request,error
import re
url = "http://desk.zol.com.cn/1920x1080/"
urls = []
urls.append(url)
for i in range(2,21):
urls.append(url+"%r.html" % i)
2.获取每张壁纸的页面:
for url in urls:
try:
# 打开页面
response = request.urlopen(url)
# 此时的html是'byte'类型
html = response.read()
# 转换成字符串
html = str(html)
pattern = re.compile(r'<a.*? href="(.*?)".*?>.*?</a>')
# 匹配<a>标签中的href地址
imglist = re.findall(pattern,html)
truelist = []
for item in imglist:
if re.match(r'^\/bizhi\/',item):
# 注意观察会发现有大幅壁纸的页面地址均以/bizhi/开头
truelist.append(item) # 筛选掉其他无关页面
# 处理HTTPError
except error.HTTPError as e:
print(e.reason)
# 处理URLError
except error.URLError as e:
print(e.reason)
except: #预防出现其他未知错误
pass
3.对每张壁纸,获取其地址并下载到本地:
x = 0
for wallpaperpage in truelist:
try:
url1 = "http://desk.zol.com.cn"+wallpaperpage
response1 = request.urlopen(url1)
# 打开壁纸的页面,相当于在浏览器中单击壁纸名
html1 = response1.read()
html1 = str(html1)
pattern1=re.compile(r'<a.*?id="1920x1080" href="(.*?)".*?>.*?</a>')
# 匹配<a>标签中的id为1920 ×1080的地址,相当于在浏览器中选择1920×1080分辨率
urllist = re.findall(pattern1,html1)
html2 = str(request.urlopen("http://desk.zol.com.cn"+urllist[0]).read())
pattern2 = re.compile(r'<img.*? src="(.*?)"')
# 获取高清图片的地址
wallpaperurl = re.findall(pattern2,html2)
# 下载图片存储到D://Practice/文件夹,命名为x.jpg
request.urlretrieve(wallpaperurl[0],"D://Practice/%r.jpg" % x)
x += 1
except error.HTTPError as e:
print(e.reason)
except error.URLError as e:
print(e.reason)
except:
pass
当你,看完以上代码段;是不是觉得使用python很直接,很方便的就搞定了呢?