Python抓取网页中的图片到本地
2016-08-28 10:20
543 查看
今天在网上找了个从网页中通过图片URL,抓取图片并保存到本地的例子:
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: xixihuang # Date : 2016/08/28 10:12 AM # Desc: 抓取网页,获取图片URL,抓取图片内容并保存到本地。 import os import uuid import urllib2 import cookielib '''获取文件后缀名''' def get_file_extension(file): return os.path.splitext(file)[1] '''創建文件目录,并返回该目录''' def mkdir(path): # 去除左右两边的空格 path=path.strip() # 去除尾部 \符号 path=path.rstrip("\\") if not os.path.exists(path): os.makedirs(path) return path '''自动生成一个唯一的字符串,固定长度为36''' def unique_str(): return str(uuid.uuid1()) ''' 抓取网页文件内容,保存到内存 @url 欲抓取文件 ,path+filename ''' def get_file(url): try: cj=cookielib.LWPCookieJar() opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) req=urllib2.Request(url) operate=opener.open(req) data=operate.read() return data except BaseException, e: print e return None ''' 保存文件到本地 @path 本地路径 @file_name 文件名 @data 文件内容 ''' def save_file(path, file_name, data): if data == None: return mkdir(path) if(not path.endswith("/")): path=path+"/" file=open(path+file_name, "wb") file.write(data) file.flush() file.close() #获取文件后缀名 print get_file_extension("123.jpg"); #創建文件目录,并返回该目录 #print mkdir("d:/ljq") #自动生成一个唯一的字符串,固定长度为36 print unique_str() url="http://qlogo1.store.qq.com/qzone/416501600/416501600/100?0"; save_file("D:/test/", "123.jpg", get_file(url))
相关文章推荐
- 利用python正则表达式抓取网页中的图片到本地
- 黄聪:python访问抓取网页常用命令(保存图片到本地、模拟POST、GET、中文编码问题)
- 黄聪:python访问抓取网页常用命令(保存图片到本地、模拟POST、GET、中文编码问题)
- python抓取网页中图片并保存到本地
- python抓取网页中图片并保存到本地
- python 解析网页,将抓取到的图片保存到本地
- python抓取网页中图片并保存到本地
- python抓取网页中图片并保存到本地
- python抓取网页中图片并保存到本地
- python抓取网页中图片并保存到本地
- python爬虫之抓取网页中的图片到本地
- python抓取网页图片
- Python爬虫抓取网页图片
- python 保存网页图片到本地
- Python3 抓取网页中的图片
- python网络爬虫,抓取网页图片
- python抓取网页中的图片示例
- 抓取网页信息,下载网络图片到本地
- python抓取网页图片 python爬虫实例
- python抓取网页中的图片示例