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

时间:2017-02-25 11:55:10

标签: python sockets http python-asyncio

我试图用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()

它只获得标题,但没有内容!

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'

1 个答案:

答案 0 :(得分:0)

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

我用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并从中获得。如果您有任何问题,请告诉我。