python爬虫基础爬取图片

本文介绍了一种使用Python爬虫技术抓取图片的方法,通过构建特定的报头和正则表达式,从目标网站上批量下载图片到本地路径。代码示例详细展示了如何使用urllib.request模块实现这一过程。

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

用于记录python爬虫学习的案例

利用python爬虫,基础爬取图片

代码如下:

import urllib.request
import re
header={
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"
}
#构建报头
opener=urllib.request.build_opener()
opener.addheaders=header.items()
#安装为全局
urllib.request.install_opener(opener)
url="https://read.douban.com/provider/63750322/"
html=urllib.request.urlopen(url).read().decode("utf-8","ignore")
#构造正则表达式
pat='<img width="110px" height="165px" src="https://(.*?)"'
data=re.compile(pat,re.S).findall(html)
for i in range(0,len(data)):
    localpath="E:/python_practice/image/image"+str(i+1)+".jpg"
    this_url="https://%s"%data[i]
    urllib.request.urlretrieve(this_url,filename=localpath)

这样以后就可以爬取图片,爬取图片展示如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值