python自动保存图片_利用Python编写自动批量保存彼岸图网图片程序

该博客展示了如何使用Python的urllib和lxml库从特定板块抓取并下载多页图片。通过解析HTML,利用XPath表达式获取图片链接,并保存到本地文件系统。代码中包含了异常处理,确保爬虫稳定运行。
摘要由CSDN通过智能技术生成

import urllib.request

from lxml import etree

plate = "4kyouxi"   #选择要爬取的版块

pages = 1     #要爬取的页数

def image_download():

for x in range(0,pages):

try:

if(x==0):

url = "http://pic.netbian.com/"+plate+"/index.html"    #板块图片url

urldata = urllib.request.urlopen(url).read().decode("gbk")  #获取数据

treeurldata = etree.HTML(urldata)  #转化成被xpath识别和匹配的对象,并赋值给treeurldata变量

urllist = treeurldata.xpath("//ul[@class='clearfix']/li/a/@href")     #xpath表达式

for y in range(0,len(urllist)):

image_url = "http://pic.netbian.com"+urllist[y]   #图片详情页url

image_data = urllib.request.urlopen(image_url).read().decode("gbk")

treeimage_data = etree.HTML(image_data)

title = treeimage_data.xpath("//h1/text()")

imagedownload_urldata = treeimage_data.xpath("//div[@class='photo-pic']/a/img/@src")

imagedownload_url = "http://pic.netbian.com"+str(imagedownload_urldata[0])

#print(title)

#print(imagedownload_url+"\n")

localfile = "C:\\Users\\MichstaBe\\Desktop\\image\"+"第"+str(x+1)+"页"+"第"+str(y)+"张"+".jpg"      #保存地址

urllib.request.urlretrieve(imagedownload_url,filename=localfile)

print("正在爬取并保存:"+str(title[0])+"\n")

#time.sleep(0.5)

else:

url = "http://pic.netbian.com/"+plate+"/index_"+str(x+1)+".html"

urldata = urllib.request.urlopen(url).read().decode("gbk")  #获取数据

treeurldata = etree.HTML(urldata)  #转化成被xpath识别和匹配的对象,并赋值给treeurldata变量

urllist = treeurldata.xpath("//ul[@class='clearfix']/li/a/@href")     #xpath表达式

for y in range(0,len(urllist)):

image_url = "http://pic.netbian.com"+urllist[y]   #图片详情页url

image_data = urllib.request.urlopen(image_url).read().decode("gbk")

treeimage_data = etree.HTML(image_data)

title = treeimage_data.xpath("//h1/text()")

imagedownload_urldata = treeimage_data.xpath("//div[@class='photo-pic']/a/img/@src")

imagedownload_url = "http://pic.netbian.com"+str(imagedownload_urldata[0])

#print(title)

#print(imagedownload_url)

localfile = "C:\\Users\\MichstaBe\\Desktop\\image\"+"第"+str(x+1)+"页"+"第"+str(y)+"张"+".jpg"      #保存地址

urllib.request.urlretrieve(imagedownload_url,filename=localfile)

print("正在爬取并保存:"+str(title[0])+"\n")

#time.sleep(0.5)

except Exception as err:

pass

image_download()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值