使用python网络库下载
下载1000次网页资源
1,普通循环方式下载1000次,非常慢
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import time
import urllib
import urllib2 total_times = 1000 def worker(url):
try:
f = urllib2.urlopen(url,timeout=10800)
body = f.read()
except:
print sys.exc_info()
return 0
return 1 if __name__ == "__main__": for i in range(total_times):
url = "http://web.kuaipan.cn/static/images/pc.png"
worker(url) #root:~/test # time ./c.py
#real 4m6.700s
#user 0m1.192s
#sys 0m1.736s
2,使用进程池下载,有点慢
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import time
import urllib
import urllib2
import multiprocessing total_times = 1000 def worker(url):
try:
f = urllib2.urlopen(url,timeout=10800)
body = f.read()
except:
print sys.exc_info()
return 0
return 1 if __name__ == "__main__": pool_size = multiprocessing.cpu_count() * 2
pool = multiprocessing.Pool(processes=pool_size) for i in range(total_times):
url = "http://web.kuaipan.cn/static/images/pc.png"
pool.apply_async(worker, (url,)) pool.close()
pool.join() #root:~/test # time ./pc.py
#real 1m43.668s
#user 0m1.480s
#sys 0m1.628s
3,使用twisted网络库,同样发起1000次请求,耗时减少为15s左右,性能提升很多,很快
#!/usr/bin/python from sys import argv
from pprint import pformat #from twisted.internet.task import react
from twisted.internet import reactor
from twisted.web.client import Agent, readBody
from twisted.web.http_headers import Headers total_times = 1000
times = 0 def cbRequest(response):
#print 'Response version:', response.version
#print 'Response code:', response.code
#print 'Response phrase:', response.phrase
#print 'Response headers:'
#print pformat(list(response.headers.getAllRawHeaders()))
d = readBody(response)
d.addCallback(cbBody)
return d def cbBody(body):
#print 'Response body:'
#print body
data = body def cbShutdown(ignored):
global times
times = times + 1
if total_times - 1 < times:
reactor.stop() def curl(url):
agent = Agent(reactor)
d = agent.request(
'GET', url,
Headers({'User-Agent': ['Twisted Web Client Example']}),
None)
d.addCallback(cbRequest)
d.addBoth(cbShutdown)
return d if __name__ == '__main__': for i in range(total_times):
curl("http://web.kuaipan.cn/static/images/pc.png") reactor.run() #root:~/test # time ./tc.py
#real 0m15.480s
#user 0m3.596s
#sys 0m0.720s
4,使用twisted网络库长连接,耗时也是很少,很快
#!/usr/bin/python from sys import argv
from pprint import pformat #from twisted.internet.task import react
from twisted.internet import reactor
from twisted.web.http_headers import Headers from twisted.internet import reactor
from twisted.internet.defer import Deferred, DeferredList
from twisted.internet.protocol import Protocol
from twisted.web.client import Agent, HTTPConnectionPool total_times = 1000
times = 0 class IgnoreBody(Protocol):
def __init__(self, deferred):
self.deferred = deferred def dataReceived(self, bytes):
pass def connectionLost(self, reason):
self.deferred.callback(None) def cbRequest(response):
#print 'Response code:', response.code
finished = Deferred()
response.deliverBody(IgnoreBody(finished))
return finished pool = HTTPConnectionPool(reactor)
agent = Agent(reactor, pool=pool) def requestGet(url):
d = agent.request('GET', url)
d.addCallback(cbRequest)
return d def cbShutdown(ignored):
global times
times = times + 1
if total_times - 1 < times:
reactor.stop() def curl(url):
agent = Agent(reactor)
d = agent.request(
'GET', url,
Headers({'User-Agent': ['Twisted Web Client Example']}),
None)
d.addCallback(cbRequest)
d.addBoth(cbShutdown)
return d for i in range(total_times):
curl("http://web.kuaipan.cn/static/images/pc.png") reactor.run() #root:~/test # time ./tpc.py
#real 0m12.817s
#user 0m3.508s
#sys 0m0.528s
更多twisted参考:https://twistedmatrix.com/documents/current/web/howto/client.html#auto4
golang使用循环下载方式,和python使用循环下载方式耗时差不多,4分钟时间,瓶颈应该在网络
package main import (
"fmt"
"net/http"
"io/ioutil"
) var totaltimes = func worker(url string) {
response, err := http.Get(url)
if err != nil {
return
}
defer response.Body.Close()
body, _ := ioutil.ReadAll(response.Body)
fmt.Println(len(body))
} func main() { for i := ; i < totaltimes;i ++ {
worker("http://web.kuaipan.cn/static/images/pc.png")
}
} //root:~/test # time ./got > goresult
//
//real 4m45.257s
//user 0m0.628s
//sys 0m0.632s
golang使用协程池方式模拟下载1000次,性能也要差很多(而且容易出现网络错误,最近出的go version go1.2rc4 linux/amd64要好一点 ,go1.1问题很多)
package main import (
"fmt"
"net/http"
"io/ioutil"
"sync"
) var totaltimes =
var poolsize = func worker(linkChan chan string, wg *sync.WaitGroup) {
// Decreasing internal counter for wait-group as soon as goroutine finishes
defer wg.Done() for url := range linkChan {
// Analyze value and do the job here
response, err := http.Get(url)
if err != nil {
return
}
defer response.Body.Close()
body, _ := ioutil.ReadAll(response.Body)
fmt.Println(len(body))
//fmt.Println("Resp code", response.StatusCode)
}
} func main() {
var i int lCh := make(chan string)
wg := new(sync.WaitGroup)
// Adding routines to workgroup and running then
for i := ; i < poolsize; i++ {
wg.Add()
go worker(lCh, wg)
} for i = ; i < totaltimes;i ++ {
lCh <- "http://web.kuaipan.cn/static/images/pc.png"
}
close(lCh)
// Waiting for all goroutines to finish (otherwise they die as main routine dies)
wg.Wait()
} //root:~/test # time ./gotest > goresult
//
//real 0m25.250s
//user 0m0.772s
//sys 0m0.380s
twisted支持定时器,我们可以用来动态添加任务
from twisted.web.client import getPage
from twisted.internet import reactor class Getter(object): def __init__(self):
self._sequence = 0
self._results = []
self._errors = [] def add(self, url):
d = getPage(url)
d.addCallbacks(self._on_success, self._on_error)
d.addCallback(self._on_finish)
self._sequence += 1 def _on_finish(self, *narg):
self._sequence -= 1
print len(self._results), len(self._errors)
# if not self._sequence:
# reactor.stop() _on_success = lambda self, *res: self._results.append(res)
_on_error = lambda self, *err: self._errors.append(err) def run(self):
reactor.run()
return self._results, self._errors def jobtimer():
for url in ('http://www.google.com', 'http://www.yahoo.com', 'http://www.baidu.com'):
g.add(url)
reactor.callLater(1,jobtimer) reactor.callLater(2,jobtimer) #定时添加任务
g = Getter()
results, errors = g.run() #print len(results)
#print len(errors)
使用python网络库下载的更多相关文章
- 基于协程的Python网络库gevent
import gevent def test1(): print 12 gevent.sleep(0) print 34 def test2(): print 56 gevent.sleep(0) p ...
- Python网络爬虫 - 下载图片
下载博客园的logo from urllib.request import urlretrieve from urllib.request import urlopen from bs4 import ...
- python 第三方库下载
C:\Python27\Scripts 路径下: easy_install.exe: C:\Python27\Scripts>easy_install.exe pycrypto pip.exe: ...
- python 第三方库下载地址
http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml
- python基于协程的网络库gevent、eventlet
python网络库也有了基于协程的实现,比较著名的是 gevent.eventlet 它两之间的关系可以参照 Comparing gevent to eventlet, 本文主要简单介绍一下event ...
- python常用库
本文由 伯乐在线 - 艾凌风 翻译,Namco 校稿.未经许可,禁止转载!英文出处:vinta.欢迎加入翻译组. Awesome Python ,这又是一个 Awesome XXX 系列的资源整理,由 ...
- 156个Python网络爬虫资源
本列表包含Python网页抓取和数据处理相关的库. 网络相关 通用 urllib - 网络库(标准库) requests - 网络库 grab - 网络库(基于pycurl) pycurl - 网络库 ...
- Python常用库大全
环境管理 管理 Python 版本和环境的工具 p – 非常简单的交互式 python 版本管理工具. pyenv – 简单的 Python 版本管理工具. Vex – 可以在虚拟环境中执行命令. v ...
- python的库小全
环境管理 管理 Python 版本和环境的工具 p – 非常简单的交互式 python 版本管理工具. pyenv – 简单的 Python 版本管理工具. Vex – 可以在虚拟环境中执行命令. v ...
随机推荐
- .NET软件开发与常用工具清单
[工欲善其事,必先利其器]软件开发的第一步就是选择高效.智能的工具. 下面列出的工具软件能辅助提高工作效率. 开发类工具 微软.Net平台下的集成开发环境:Visual Studio. Visual ...
- 原生js封装table表格操作,获取任意行列td,任意单行单列方法
V1.001更新增加findTable-min.js 本次更新,优化了代码性能方面,增加了部分新功能,可以获取多个table表格批量操作. 考虑到本人后面的项目中可能涉及到大量的表格操作,提前先封了 ...
- MySQL中的insert ignore into, replace into等的一些用法小结(转)
MySQL中的insert ignore into, replace into等的一些用法总结(转) 在MySQL中进行条件插入数据时,可能会用到以下语句,现小结一下.我们先建一个简单的表来作为测试: ...
- Linux学习之开机启动
当我们打开计算机电源,计算机会自动从主板的BIOS(Basic Input/Output System)读取其中所存储的程序.这一程序通常知道一些直接连接在主板上的硬件(硬盘,网络接口,键盘,串口,并 ...
- MySql级联操作
转自:http://blog.csdn.net/codeforme/article/details/5539454 外键约束对子表的含义: 如果在父表中找不到候选键,则不允许在子表上进行i ...
- hadoop搭建杂记:Linux下hostname的更改办法
VirtualBox搭建hadoop伪分布式模式:更改hostname VirtualBox搭建hadoop伪分布式模式:更改hostname master: ip:192.168.56.120 机器 ...
- mssql索引使用情况查询
可通过查询dm_db_index_usage_stats表取得对应表索引被使用次数. 列名 数据类型 说明 database_id smallint 在其中定义表或视图的数据库的 ID. object ...
- 通过web远程访问服务器的ipython
如果想同过一个Web浏览器的方式远程访问服务器上的ipython notebook sever,可通过下面的步骤实现. 服务器:ubuntu14.04 server 客户端:windows/unix/ ...
- vcredist作用
一.vcredist作用: vcredist_x86.exe是微软公司Visual C++的32位运行时库,包含了一些Visual C++的库函数. vcredist_x64.exe是微软公司Visu ...
- Consuming Hidden WCF RIA Services
原文 http://codeseekah.com/2013/07/05/consuming-hidden-wcf-ria-services/ A Silverlight application mad ...