python爬虫爬取wallpapers最新壁纸

python爬虫爬取wallpapers最新壁纸

详细教程请访问:https://www.bilibili.com/video/av58978561/

详细教程请访问:https://www.bilibili.com/video/av58978561/

import requests #这个包里有打开网页的包
from bs4 import BeautifulSoup #这个包里有html解析器
def getimg(url,path,name):#将步骤3封装成函数 参数(图片网址,路径,名字)
    with requests.get(url) as resp:#打开图片
        with open(path+'/'+name+'.jpg','wb') as f:#打开路径,准备写入图片
            f.write(resp.content)#将图片以传进来的名字以wb(w:写入 b:二进制方式)写入路径

def getdurl(url,l,w):#步骤2 参数(每一页的网址,图片长度,图片宽度)
    with requests.get(url) as resp:#打开网址
        html=resp.text#获取html代码
    soup=BeautifulSoup(html,'html.parser')#将代码用bs4进行解析
    h1=soup.select('h1')#找到html代码中标签为h1(html中h1代表标题)的赋值给变量h1 这样我们就找到了所有图片的名字,但是还有一个网页的标题Latest Wallpapers
    for i in h1:#for循环
        if i.text=='Latest Wallpapers':
            continue#去掉网页标题
        n=i.text
        imgurl='http://wallpaperswide.com/download/'+n.replace(' ','_').lower()+'-'+str(l)+'x'+str(w)
        #拼接网址,将名字中空格换成下划线,所有字母换小写
        # print(imgurl)
        print('正在下载'+n+'。。。')#提示信息
        getimg(imgurl,'D:\编程\python\wallpapers',n)#调用步骤三函数循环下载
        print(n+'下载完成。。。')#提示信息
        # url='http://wallpaperswide.com/download/Cyberpunk2077-800x480'

if __name__=='__main__':#此程序作为主程序运行
    for i in range(2):#外循环,从第一页循环至第十页,这里的10可以改成别的
        getdurl('http://wallpaperswide.com/latest_wallpapers/page/'+str(i+1)+'.html',1366,768)#拼接网址调用步骤二函数
    
发布了25 篇原创文章 · 获赞 1 · 访问量 502

猜你喜欢

转载自blog.csdn.net/qq_43985303/article/details/95728389