在 python 中,我将如何发出 http 请求而不是等待响应。我不关心取回任何数据,我只需要向服务器注册一个页面请求。
现在我使用这段代码:
urllib2.urlopen("COOL WEBSITE")
但显然这会暂停脚本,直到返回响应,我只想发出请求并继续。
我该怎么做?
最佳答案
你在这里想要的是Threading 或Asynchronous。
线程:
- 将对
urllib2.urlopen()
的调用包装在threading.Thread()
中
例子:
from threading import Thread
def open_website(url):
return urllib2.urlopen(url)
Thread(target=open_website, args=["http://google.com"]).start()
异步:
- 不幸的是,在 Python 标准库中没有执行此操作的标准方法。
使用 requests有这种支持的图书馆。
例子:
from requests import async
async.get("http://google.com")
还有第三个选项使用 restclient图书馆有 内置(有一段时间)异步支持:
from restclient import GET
res = GET("http://google.com", async=True, resp=True)
关于Python & URLLIB2 - 请求网页但不等待响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20580896/