Python爬取图片并保存本地

本文介绍如何使用Python的requests库抓取指定网站的行业案例图片及链接,包括网页请求、数据解析、CSV文件保存及图片下载全过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

好久没用requests写爬虫了,因为是国内的网站,展示没有使用代理IP,而且爬取的数据不多。
1、第一步将要爬取的网页链接爬取下来。这句话有些矛盾。
url=‘http://www.supe.com.cn/index.php/Project/index’,就这这个各个行业的链接抓取下来,然后保存到本地,
在这里插入图片描述
代码是

import requests

headers={
    'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'
}

# 要访问的目标页面
url='http://www.supe.com.cn/index.php/Project/index'
resp = requests.get(url, headers=headers,)
res_html=resp.text
#对网页进行解析,并获取想要的内容,这里是用xpath的路径选择
from scrapy.selector import Selector
select=Selector(resp)
area=select.xpath('/html/body//ul[@class="nav clearfix"]//a/text()').extract() #获取分类的类别 ['地坪案例', '聚脲案例']
area_herf=select.xpath('/html/body//ul[@class="nav clearfix"]//a/@href').extract() # ['/index.php/Project/index/cat_id/14', '/index.php/Project/index/cat_id/15']

#这里定义一个保存为csv的函数
import csv
def save_csv(data_list):
    file = csv.writer(open('link.csv', 'a', newline='', encoding='utf-8'))
    file.writerow(data_list)

#获取各个行业的名称以及链接
hangye=select.xpath('/html/body/div[@class="main"]//div[@class="case bgf"]//li')
for li in hangye:
    hangye_href=li.xpath('./a/@href').extract_first()
    hangye_name=li.xpath('./a/text()').extract_first()
    hangye_href_2=hangye_href+'/p/2'
    print(hangye_name,hangye_href,hangye_href_2)
    
    if hangye_href==None:
        break
    save_csv([hangye_name,hangye_href,hangye_href_2]) #传入一个列表,按行写入

保存的各个行业的链接如下:

在这里插入图片描述

二、通过读取link的csv文件获取每个行业的图片链接和标题文字
在这里插入图片描述
此时保存的时候需要你提前在项目的目录先新建一个保存csv文件的文件夹,如图:
在这里插入图片描述
代码如下:

# -*- coding: utf-8 -*-
# @Time    : 2020/3/4 9:43
# @Author  : 结尾!!
# @FileName: 抓取工程案例的图片-链接.py
# @Software: PyCharm
import csv
import time
import requests
from scrapy.selector import Selector
def parser_html(hangye,url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'
    }
    # 要访问的目标页面
    resp = requests.get(url, headers=headers, )
    print(url,resp.status_code)
    select = Selector(resp)
    #获取所有的行业以及行业的链接
    # hangye = select.xpath('/html/body/div[@class="main"]//div[@class="case bgf"]//li') #调用自身的网页链接是一样的

    # 解析图片和图片的文字  //*[@id="vid_45"]
    anli_tu = select.xpath('//*[@id="vid_45"]/ul//li')
    for tu_li in anli_tu:
        img = tu_li.xpath('./div[@class="picall"]/img/@src').extract_first()
        di_biao = tu_li.xpath('./div[@class="picall"]//em/text()').extract_first()
        jie_shao = tu_li.xpath('./div[@class="picall"]//p/text()').extract_first()
        save_csv(hangye,[img,di_biao,jie_shao])

def save_csv(filename,data_list):
    #需要提前新建一个保存csv文件的图片
    file = csv.writer(open(f'./project_case/{filename}.csv', 'a', newline='', encoding='utf-8'))
    file.writerow(data_list)



if __name__ == '__main__':
    file=open('./link.csv',encoding='utf-8')
    links=file.readlines()
    #构造链接http://www.supe.com.cn/index.php/Project/index/cat_id/15
    for link in links:
        print(link.split(','))
        line_list=link.split(',')
        link_1='http://www.supe.com.cn'+line_list[1]
        link_2='http://www.supe.com.cn'+line_list[2].strip()
        parser_html(line_list[0],link_1)
        time.sleep(2)
        parser_html(line_list[0],link_2)
        time.sleep(2)



三、就可以按照保存的图片链接,和内容进行下载图片了


import requests
def request_download(file,list_data):
    file_name=file[:-4]
    os.makedirs(f'./project_case/{file_name}/',exist_ok=True) #创建文件夹
    IMAGE_URL='http://www.supe.com.cn'+list_data[0]
    print(IMAGE_URL)
    header={
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'

    }
    r = requests.get(IMAGE_URL,headers=header)
    with open(f'./project_case/{file_name}/{list_data[1]}.jpg', 'wb') as f:
        f.write(r.content)

import os
if __name__ == '__main__':

    file_names=os.listdir('./project_case')
    print(file_names)
    for file_each in file_names:
        print(file_each)
        if file_each.endswith('.csv'):
            file=open(f'./project_case/{file_each}',encoding='utf-8')
            links=file.readlines()
            for line in links:
                print(line.split(','))
                data=line.split(',')
                request_download(file_each,data)
            # time.sleep(1)


最后效果如下:每个文件夹下都是对应的csv文件中的图片,以及可以查找对应的图片描述
在这里插入图片描述
在这里插入图片描述
以上就是全部过程,给requests加代理,这个使用阿布云代上的代理案例代码,,这里不做演示了。。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_43351935

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值