python使用re, os, httplib, urllib批量下载网页上的图片
2015-05-30 09:55
246 查看
import re ,httplib, urllib, os conn = httplib.HTTPConnection("www.njupt.edu.cn") """ 下面这行代码可以用httplib提供的其他几个方法实现 但是要求读者对http协议有一定的了解,示例如下: dataBody = urllib.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'}) conn.putrequest("POST", "/") conn.putheader("HOST", "www.njupt.edu.cn") conn.putheader("Content-Type", "application/x-www-form-urlencoded") conn.putheader("Content-Length", str(len(databody))) conn.putheader("Accept", "text/plain") conn.endheaders() conn.send(dataBody) """ """ request()方法也可以携带头部字段,携带的头部字段会自动覆盖同名的头部字段 对于POST方法的Content-Length字段由方法自己计算添加,也可以由我们自己添加 例如: params = urllib.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'}) headers = {"Content-type": "application/x-www-form-urlencoded", "Content-Length": str(len(params)) "Accept": "text/plain"} conn.request("POST", "/", params, headers) """ """ 上述两种方法没有明显差别 """ conn.request("GET", "/") response = conn.getresponse() htmlPage = response.read() conn.close() """ 利用re模块正则表达式提取html网页中img地址(对html不熟,可能这块会有问题) 推荐书籍《精通正则表达式》 """ reg = re.compile("<img *src=\"([^\"]+)\"") """ 提取网页里面的图片链接,可能会有重复的地址 """ pics = reg.findall(htmlPage) dirname = "/home/myhome/pic" os.chdir(dirname) reg1 = re.compile("http://") """ 用来提取文件名 """ reg2 = re.compile("/([^/]+\.[a-zA-Z]{3,4})$") """ tuple(set(pics))用于去重 """ for pic in tuple(set(pics)): if reg1.match(pic): filename = reg2.findall(pic)[0] urllib.urlretrieve(pic, filename) print(filename+" download completed....") else: pic = "http://www.njupt.edu.cn"+pic filename = reg2.findall(pic)[0] urllib.urlretrieve(pic, filename) print(filename+" download completed....")
另外补充几点:
(1)在后面下载图片文件时,我们如果自己构造HTTP header,那么切记要替换图片对应的HOST头值
(2)我们可以使用httpllib.request和len = int(HTTPResponse.getheader("Content-Length"))、HTTPResponse.read(len)自己读取图片数据再写入磁盘,这样我们可以重复利用一次tcp连接,下载多个图片文件,不过在此之前我们必须对所属于同一域名的图片文件进行归类再下载
相关文章推荐
- http://guoyifan163.blog.163.com/
- HTTP 400/401/403/404/500网页错误代码是什么意思
- Spring MVC使用HttpClient返回json报406错误解决办法
- 新手如何做好网络营销
- 菜鸟好文推荐(五)——理解 HTTPS 协议
- 利用HttpWebRequest实现实体对象的上传
- 颓废的战士
- Boost Asio 异步TCP服务器框架
- Reseau Mobile移动网络跟从大到小
- Réseau Donnée---搭建网络
- ssd8 网络与分布式系统实验 EXAM1
- HttpClient使用详解
- libevent evhttp_uri_get_query coredump
- (转载)VMware下网络配置三种模式对比(桥接模式,主机模式,网络地址转换)
- [Python]网络爬虫(七):Python中的正则表达式教程
- 虚拟机的三种网络模式
- ngx_http_concat_module
- javascript深入理解js闭包(摘自网络)
- 网络基本知识的总结
- Java网络编程(TCP/UDP)