Python - 使用HTTPS的urllib2异步/线程请求示例

Sea*_*tle 17 python multithreading urllib2

我有一点时间使用Python的urllib2来获取异步/线程HTTPS请求.

有没有人有一个基本的例子来实现urllib2.Request,urllib2.build_opener和urllib2.HTTPSHandler的子类?

谢谢!

nos*_*klo 11

下面的代码同时异步执行7个http请求.它不使用线程,而是使用与扭曲库的异步网络.

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()
Run Code Online (Sandbox Code Playgroud)


小智 8

有一个非常简单的方法,涉及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!"
Run Code Online (Sandbox Code Playgroud)

  • 我只想提醒一下,虽然这种方法简单快速,但在出现问题时很容易出现问题(例如:URL不可用).有在http://www.ibm.com/developerworks/aix/library/au-threadingpython/上螺纹的漂亮的初学者引导件,其包括一个异步的urllib2溶液的一个非常简单的例子. (5认同)

Cor*_*erg 5

这是一个使用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()
Run Code Online (Sandbox Code Playgroud)