基于python的urllib 库抓取网站上的图片

最近写了个爬虫实例,有python环境的话就可以直接运行了。

运行效果是这样的:

完整代码如下:

import urllib

import urllib.request

import re

import random

import time

import os

#目标网址:

imagePath="https://pic.netbian.com"

#用户代理池

uapools=[

"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.31",

"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36",

]

#//创建保存图片的目录

imageSavePath="D:\\myimg\\"

if not os.path.isdir(imageSavePath):

os.mkdir(imageSavePath)

def UA():

opener=urllib.request.build_opener()

thisua=random.choice(uapools)

ua=("User-Agent",thisua)

opener.addheaders=[ua]

urllib.request.install_opener(opener)

print("当前使用ua:"+str(thisua))

UA()

thisurl="https://pic.netbian.com/4kqiche?s=98575646"

data=urllib.request.urlopen(thisurl).read().decode("gbk","ignore")

pat=re.compile('<img src="(/uploads/.*?)".alt="(.*?)"./>')

rst=re.findall(pat,data)

for j in rst:

link=j[0]

name=j[1]

imageUrl=''.join(imagePath+link)

res=urllib.request.urlretrieve(imageUrl,imageSavePath+"\\"+name+".jpg")

print(name+".jpg 获取成功....")

相关推荐
明月_清风2 小时前
从“能用”到“专业”:构建生产级装饰器与三层逻辑拆解
后端·python
曲幽11 小时前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic
用户83562907805116 小时前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon17 小时前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly17 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent
敏编程17 小时前
一天一个Python库:pyarrow - 大规模数据处理的利器
python
Flittly19 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(4)Subagents (子智能体)
python·agent
明月_清风1 天前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风1 天前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi2 天前
08c. 检索算法与策略-混合检索
后端·python·算法