基于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=j0

name=j1

imageUrl=''.join(imagePath+link)

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

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

相关推荐
专注仿真28 分钟前
基于 AFSIM 的智能体训练:多智能体强化学习篇 —— QTRAN 算法实战
开发语言·python·算法·php·强化学习·afsim智能体·仿真训练
2601_967987372 小时前
Python类变量和实例变量(类属性和实例属性)
python·类变量·实例变量·类属性·实例属性
CyrusYiVPP2 小时前
新用户第二周还剩几个?pandas做留存率cohort分析,数据分析实战第6期
人工智能·python
岁月宁静12 小时前
五、《从零手撸 Agent》 — 什么是 Agent:从“会聊天”到“会做事”,差的就是一个循环
python·agent
梯度下降者12 小时前
Python - 函数
python·高阶函数·可调用对象·functools·嵌套作用域
starzy199014 小时前
深入理解Scala隐式参数:上下文流转
开发语言·python·scala
wuyk55515 小时前
Spider-第16讲-线程池与竞态问题
大数据·爬虫·python·elasticsearch·搜索引擎
kyle~21 小时前
FastAPI --- 将业务能力以 API 的形式提供给外部系统
python·fastapi·前后端
aiotto资源分享1 天前
Python 写 JSON 文件,程序中途退出会留下什么?
java·python·json·jsondecodeerror
梯度下降者1 天前
Python信号量,条件变量,事件学习
python·条件变量·事件·信号量·线程通信