爬虫小案例04—使用Beautiful Soup批量获取图片

步骤:
1、拿到主页面的源代码,然后提取到子页面的链接地址,href
2、通过href拿到子页面的内容,从子页面中找到图片的下载地址 src
3、下载图片

#导入需要用到的包
import requests
from bs4 import BeautifulSoup
import time
#获取源码
url = 'https://www.umei.cc/bizhitupian/weimeibizhi/'
resp = requests.get(url)
resp.encoding = resp.apparent_encoding
#将源代码交给BeautifulSoup
main_page = BeautifulSoup(resp.text,"html.parser")
#print(main_page)
#2022.10此时的页面结构可以通过该内容获取
aList = main_page.find_all("div",class_="img")
for i in aList:
    img_one = i.find("img")
    img_resp = requests.get(img_one.get("data-original"))
    img_name = img_one.get("alt").split(",")[-1]
    with open("E:/火狐下载/" + img_name + ".png",mode = "wb") as f:
        f.write(img_resp.content) #图片内容写入文件
#网页结构发生改变,此代码无法实现结果,仅供参看学习
#main_page.find("div",class_="TypeList")  #将范围第一次缩小【类名,class后要 添加 _】
aList = main_page.find("div",class_="TypeList").find_all("a")
for a in aList:
    href = a.get('href')  #直接通过get就可以拿到属性的值
    #print(href)
    #拿到子页面源代码
    child_href = 'https://www.umeitu.com/' + href    
    child_page_resp = requests.get(child_href)
    child_page_resp.encoding = child_page_resp.apparent_encoding
    child_page_text = child_page_resp.text
    #从子页面中拿到图片的下载路径
    child_page = BeautifulSoup(child_page_text,"html.parser")
    div = child_page.find("div",class_="ImageBody")
    img = div.find("img")
    src = img.get("src")
    #下载图片
    img_resp = requests.get(src)
    # img_resp.content 拿到的是字节
    img_name = src.split("/")[-1]  #url中的最后一个/后的内容,作为img的名字
    #优美图库img 是文件夹的名称,将图片放入该文件夹中,该文件夹与py文件在同一目录下
    with open("优美图库img/" + img_name,mode = "wb") as f:
        f.write(img_resp.content) #图片内容写入文件
    
    print("over!", img_name)
    time.sleep(5)
    
print("all over!!!")
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值