【发布时间】:2017-02-25 11:55:10
【问题描述】:
我正在尝试使用 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 请求,您期待什么?
-
@jonrsharpe 很好的答案,伙计。他很可能是做错了,你也否决了这个问题?如果你向他解释 HEAD 请求只是从网站收集头部,而他会寻找 GET 请求,那会更有帮助。
标签: python sockets http python-asyncio