[英]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()
它僅獲得標題,而沒有內容!
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請求將僅檢索標頭,這就是為什么僅接收標頭的原因。
我已經用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和yield from輕松地轉換為3.4。 讓我知道您是否有任何問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.