我有一段时间让异步/线程HTTPS请求使用Python的urllib2工作。Python - 使用HTTPS的urllib2异步/线程请求示例
有没有人有一个基本的例子,实现urllib2.Request,urllib2.build_opener和urllib2.HTTPSHandler的子类?
谢谢!
我有一段时间让异步/线程HTTPS请求使用Python的urllib2工作。Python - 使用HTTPS的urllib2异步/线程请求示例
有没有人有一个基本的例子,实现urllib2.Request,urllib2.build_opener和urllib2.HTTPSHandler的子类?
谢谢!
以下代码在同一时间异步执行7个http请求。 它不使用线程,而是使用异步网络与twisted库。
from twisted.web import client
from twisted.internet import reactor, defer
urls = [
'http://www.python.org',
'http://stackoverflow.com',
'http://www.twistedmatrix.com',
'http://www.google.com',
'http://launchpad.net',
'http://github.com',
'http://bitbucket.org',
]
def finish(results):
for result in results:
print 'GOT PAGE', len(result), 'bytes'
reactor.stop()
waiting = [client.getPage(url) for url in urls]
defer.gatherResults(waiting).addCallback(finish)
reactor.run()
这里是从eventlet
urls = ["http://www.google.com/intl/en_ALL/images/logo.gif",
"https://wiki.secondlife.com/w/images/secondlife.jpg",
"http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif"]
import eventlet
from eventlet.green import urllib2
def fetch(url):
return urllib2.urlopen(url).read()
pool = eventlet.GreenPool()
for body in pool.imap(fetch, urls):
print "got body", len(body)
嗨,我宁可不要将我的脚本与一个eventlet要求分开。你可以用内建的urllib2.Request,urllib2.build_opener和urllib2.HTTPSHandler的子类来做到这一点吗? – SeaTurtle 2011-04-27 21:26:00
不,这是不可能的。而且,如果我是对的,它只能在linux下运行。 – 2011-04-28 11:43:24
代码在这里是使用的urllib2(以https)和线程的例子。每个线程遍历URL列表并检索资源。
import itertools
import urllib2
from threading import Thread
THREADS = 2
URLS = (
'https://foo/bar',
'https://foo/baz',
)
def main():
for _ in range(THREADS):
t = Agent(URLS)
t.start()
class Agent(Thread):
def __init__(self, urls):
Thread.__init__(self)
self.urls = urls
def run(self):
urls = itertools.cycle(self.urls)
while True:
data = urllib2.urlopen(urls.next()).read()
if __name__ == '__main__':
main()
有一个非常简单的方法,包括对urllib2的处理程序,你可以在这里找到:http://pythonquirks.blogspot.co.uk/2009/12/asynchronous-http-request.html
#!/usr/bin/env python
import urllib2
import threading
class MyHandler(urllib2.HTTPHandler):
def http_response(self, req, response):
print "url: %s" % (response.geturl(),)
print "info: %s" % (response.info(),)
for l in response:
print l
return response
o = urllib2.build_opener(MyHandler())
t = threading.Thread(target=o.open, args=('http://www.google.com/',))
t.start()
print "I'm asynchronous!"
t.join()
print "I've ended!"
我只想提醒一下,尽管这种方法简单快捷,但当某些事情中断时(如:URL不可用),它很容易出现问题。 在http://www.ibm.com/developerworks/aix/library/au-threadingpython/上有一个很好的关于线程的初学者指南,其中包含一个非常简单的Async urllib2解决方案示例。 – stricjux 2012-05-18 12:07:53
欢迎来到SO ...做**你**有一个例子,说明你现在没有什么作用吗?可能比在这里的答案从头开始诊断更容易... – 2011-04-27 17:32:45
是否有一个规则,每个问题都必须“调试我的代码?”我的代码充满了对我不想解释的变量的疯狂引用,敏感的URL等等。对于知道如何去做的人来说,这是10行代码。 – SeaTurtle 2011-04-27 21:21:17
我看到没有接受的答案。你还对此感兴趣吗?我几天前已经解决了这个问题,所以我可以花时间用代码编写详细的答案。 – MestreLion 2014-07-29 02:19:51