简体   繁体   English

python asyncio连接获取不完整的http响应

[英]python asyncio connection gets incomplete http response

I was trying to get the content of website with 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()

It gets only the header, but no content! 它仅获得标题,而没有内容!

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'

As stated by one of the comments, you are performing a HEAD request instead of a GET request: a HEAD request will only retrieve the headers, that's why you are only receiving those. 正如其中一条注释所述,您正在执行HEAD请求而不是GET请求:HEAD请求将仅检索标头,这就是为什么仅接收标头的原因。

I've tested your code with GET instead of HEAD, and it works as you were expecting; 我已经用GET而不是HEAD测试了您的代码,它可以按您期望的那样工作; but as an advice, I'd be moving to aiohttp, your entire code would be comprised into the one below, not only nicer looking, but also way faster: 但作为建议,我将转向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()

NOTE: This is Python 3.5+ async/await style, but it can be easily translated into 3.4 with @asyncio.coroutine and yield from. 注意:这是Python 3.5+ async / await样式,但是可以使用@ asyncio.coroutine和yield from轻松地转换为3.4。 Let me know if you have any issue doing it. 让我知道您是否有任何问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM