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

Python批量爬取图片

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

Python批量爬取图片

'''
爬取图片,并且下载图片
url = 'https://pic.netbian.com/4kmeinv/'
爬取网页:requests
解析网页:beautifulsoup

url = 'https://pic.netbian.com/4kmeinv/'
url = 'https://pic.netbian.com/4kmeinv/index_2.html'
"https://pic.netbian.com/uploads/allimg/220809/101035-16600110352f43.jpg"

'''


import os
import requests
from bs4 import BeautifulSoup

# 获取网页的源代码
def craw_html(url):
    resp = requests.get(url)
    resp.encoding = 'gbk'  #  ISO-8859-1
    print(resp.status_code) # 200 页面没有做任何反扒措施
    html = resp.text
    # print(html)
    return html

# 解析图片的地址
def parse_and_download(html):
    soup = BeautifulSoup(html,'html.parser')
    imgs = soup.find_all('img')
    for img in imgs:
        src = img.get('src') # 或者:img['src]
        if "/uploads/" not in src:
            continue
        '''图片后缀没有添加域名,需要拼接一下'''
        src = f"https://pic.netbian.com{src}"

        # 首先得到图片的本地文件地址
        filename = os.path.basename(src)

        # 当我们从网上下文件、图片的时候,都用wb二进制形式
        with open(f"./美女图片/{filename}",'wb') as f:
            resp_img = requests.get(src)
            print(src)
            f.write(resp_img.content)

if __name__ == '__main__':

    '''  连接符号'''
    urls = [ 'https://pic.netbian.com/4kmeinv/'] +
          [f'https://pic.netbian.com/4kmeinv/index_{i}.html'
           for i in range(2, 11)
    ]

    for url in urls:
        print("#### 正在爬取:",url)
        html = craw_html(url)
        parse_and_download(html)


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

版权所有 (c)2021-2022 wk8.com.cn

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