我在这里遇到一些麻烦,以了解线程如何工作或用它构建一些东西。
我需要下载几个网页,更改链接上的一个值(简单部分)并获取一些信息,但我正在使用'while'并且下载一个类似60kb的网站需要大约1秒或更长时间。我的网络5mb ..
有人可以提供关于如何做类似事情的简单示例吗?
答案 0 :(得分:3)
来自Advanced Usage: Asynchronous Requests
from requests import async
urls = [
'http://python-requests.org',
'http://httpbin.org',
'http://python-guide.org',
'http://kennethreitz.com'
]
rs = [async.get(u) for u in urls]
async.map(rs)
这不是使用线程,但工作方式相同 - 同时发出请求。
答案 1 :(得分:0)
摘自here
#!/usr/bin/env python
import Queue
import threading
import urllib2
import time
hosts = ["http://yahoo.com", "http://google.com", "http://amazon.com",
"http://ibm.com", "http://apple.com"]
queue = Queue.Queue()
class ThreadUrl(threading.Thread):
"""Threaded Url Grab"""
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
while True:
#grabs host from queue
host = self.queue.get()
#grabs urls of hosts and prints first 1024 bytes of page
url = urllib2.urlopen(host)
print url.read(1024)
#signals to queue job is done
self.queue.task_done()
start = time.time()
def main():
#spawn a pool of threads, and pass them queue instance
for i in range(5):
t = ThreadUrl(queue)
t.setDaemon(True)
t.start()
#populate queue with data
for host in hosts:
queue.put(host)
#wait on the queue until everything has been processed
queue.join()
main()
print "Elapsed Time: %s" % (time.time() - start)