Python3抓取网页图片

本文介绍了一个使用Python编写的简单脚本,该脚本可以从指定的网页上抓取所有图片链接,并将其下载到本地目录中。通过正则表达式匹配图片URL,利用urllib库完成下载任务。

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

# -*- coding: utf-8 -*-
# @Author: Mayuko
# @Date:   2017-01-24 15:09:23
# @Last Modified by:   Mayuko
# @Last Modified time: 2017-01-26 14:09:06
import urllib.request
import socket
import re
import sys
import os
import math
targetDir = r"D:\images"


def destFile(path):
    if not os.path.isdir(targetDir):
        os.mkdir(targetDir)
    pos = path.rindex('/')
    t = os.path.join(targetDir, path[pos + 1:])
    return t

if __name__ == "__main__":
        hostname = "http://vscom.mayuko.cn/"
        req = urllib.request.Request(hostname)
        webpage = urllib.request.urlopen(req)
        contentBytes = webpage.read()
        for link, t in set(re.findall(r'(http://[^\s]*?(jpg))', str(contentBytes))):
            print("Cache the images of " + link)
            urllib.request.urlretrieve(link, destFile(link))

print("Cache done")
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值