python asyncio 连接得到不完整的 http 响应

python asyncio connection gets incomplete http response

我试图用 python asyncio 获取网站内容。

import asyncio
import urllib.parse

@asyncio.coroutine
def get(url):
    url = urllib.parse.urlsplit(url)
    connect = asyncio.open_connection(url.hostname, 80)
    reader, writer = yield from connect
    request = ('HEAD {path} HTTP/1.1\r\n'
             'Host: {hostname}\r\n'
             'Accept:*/*\r\n'
             '\r\n').format(path=url.path or '/', hostname=url.hostname)
    writer.write(request.encode('latin-1'))
    response = yield from reader.read()
    print(response)
    writer.close()

url = 'http://www.example.com'
loop = asyncio.get_event_loop()
tasks = asyncio.ensure_future(get(url))
loop.run_until_complete(tasks)
loop.close()

只得到header,没有内容!

b'HTTP/1.1 200 OK\r\nAccept-Ranges: bytes\r\nCache-Control: max-age=604800\r\nContent-Type: text/html\r\nDate: Sat, 25 Feb 2017 11:44:26 GMT\r\nEtag: "359670651+ident"\r\nExpires: Sat, 04 Mar 2017 11:44:26 GMT\r\nLast-Modified: Fri, 09 Aug 2013 23:54:35 GMT\r\nServer: ECS (rhv/818F)\r\nX-Cache: HIT\r\nContent-Length: 1270\r\n\r\n'

如其中一条评论所述,您执行的是 HEAD 请求而不是 GET 请求:HEAD 请求只会检索 headers,这就是您只接收这些的原因。

我已经用 GET 而不是 HEAD 测试了你的代码,它按你的预期工作;但作为一个建议,我会转向 aiohttp,你的整个代码将包含在下面的代码中,不仅看起来更好看,而且速度更快:

import asyncio
import aiohttp


async def get(loop, url):
    async with aiohttp.request('GET', url, encoding='latin-1') as response:
        html = await response.text()
        print(html)

url = 'http://www.example.com'
loop = asyncio.get_event_loop()
loop.run_until_complete(get(loop, url))
loop.close()

注意:这是 Python 3.5+ async/await 风格,但可以使用 @asyncio.coroutine 轻松转换为 3.4 并从中产生。如果您有任何问题,请告诉我。