0
点赞
收藏
分享

微信扫一扫

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

滚过红尘说红尘 2022-02-26 阅读 104
爬虫python

步骤:
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)
#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 条评论