栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python爬虫学习——爬取图片并保存(十一)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python爬虫学习——爬取图片并保存(十一)

Python爬虫学习

文章目录

Python爬虫学习一、查看二、具体实现总结

一、查看

1、查看页面源代码是否有相关信息
2、一般得图片都包含子页面链接
3、提取子页面链接
4、获取下载链接

二、具体实现
import requests
from bs4 import BeautifulSoup
import time
domain='https://unsplash.com/'
url='https://unsplash.com/t/3d-renders'
resp=requests.get(url)
#print(resp.text
resp.encoding='utf-8' #解码
wangzhi_list=[]
res=resp.text
obj=re.compile(r'.*?href="(?P.*?)"',re.S)
rrr=obj.finditer(res)
for i in rrr:
    #print(i.group('lianjie'))
    wangzhi=domain+i.group('lianjie') #合成网址
    #print(wangzhi)
    wangzhi_list.append(wangzhi)
#拿到子页面的源代码
for lj in wangzhi_list:
    resp1 = requests.get(lj)
    resp1.encoding = 'utf-8'
    page = BeautifulSoup(resp1.text,"html.parser")
    h=page.find("div",attrs={"class":"mef9R"})#class是python关键字
    dat=h.find('a')
    dat1=dat.get('href')
    #下载图片 请求地址
    print(dat1)
    src=requests.get(dat1)
 #   print('1')
    mingzi=dat1.split("/")
   # print(mingzi[4])
    # img_resp.content #这里拿到的是字节
    #保存图片
    with open("img/"+mingzi[4],mode='wb') as f :
        f.write(src.content)
        print("over")
        time.sleep(1)
print('allover')
f.close()


代码和前几章都差不多,就是复制了一点

总结

Re解析和bs4解析,我觉得这两种解析方式各有各的好处,re解析很简单,可以用于服务器渲染和客户端渲染,而bs4解析就是一个标签 通过属性进行筛选确定,bs4解析在客户端渲染的时候并不是很好用

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/739566.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号