基于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 获取成功....")

相关推荐
用户8356290780517 小时前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng89 小时前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi9 小时前
Chapter 2 - Python中的变量和简单的数据类型
python
JordanHaidee9 小时前
Python 中 `if x:` 到底在判断什么?
后端·python
ServBay10 小时前
10分钟彻底终结冗长代码,Python f-string 让你重获编程自由
后端·python
闲云一鹤10 小时前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi
Rockbean11 小时前
用40行代码搭建自己的无服务器OCR
服务器·python·deepseek
曲幽12 小时前
FastAPI + Ollama 实战:搭一个能查天气的AI助手
python·ai·lora·torch·fastapi·web·model·ollama·weatherapi
用户606487671889612 小时前
国内开发者如何接入 Claude API?中转站方案实战指南(Python/Node.js 完整示例)
人工智能·python·api
只与明月听13 小时前
RAG深入学习之Chunk
前端·人工智能·python