python下载图片

本文分享了使用Python进行网页图片下载的实战经验,仅需3行代码即可完成。介绍了如何利用requests、BeautifulSoup等库解析网页源码,获取图片链接,并通过Python内置函数将图片保存到本地。

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

看完了python基础语法教程,弄了个下载网页图片的练手。下载图片只要3行代码,慢慢理解了那句人生苦短,我用python的境界

import re
import requests
from bs4 import BeautifulSoup
import xlwt
import os
def getpicurl(alist):
    imgUrlSet =[]
    for k in alist:
        urls = k.get('src')
        imgUrlSet.append(urls)
    return imgUrlSet

def downPic(picUrlSet):
    for IMAGE_URL in picUrlSet:
        r = requests.get(IMAGE_URL)
        fileName=IMAGE_URL.split('/')[-1]
        os.makedirs("d://downGirls/img/")
        with open('d://downGirls/img/'+fileName, 'wb') as f:
            f.write(r.content)

def mainMethod(url):
    response = requests.get(url)
    response.encoding = response.apparent_encoding
    # 因为网站使用的不是通用的utf-9格式,而是gzip,所以要让它判断解码格式
    html = BeautifulSoup(response.text, 'lxml')
    imgList = html.find_all('img')
    picUrlSet = getpicurl(imgList)
    downPic(picUrlSet)

mainMethod("http://www.webkfa.com/ageof18/picxjitem_web.jsp?id=255")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值