python解析http响应(字符串)
我使用的是Python2.7,我想解析已经从文本文件中提取的字符串HTTP响应字段。最简单的方法是什么?我可以使用BaseHTTPServer解析请求,但无法找到响应的内容 我的回答非常标准,格式如下python解析http响应(字符串),python,http,Python,Http,我使用的是Python2.7,我想解析已经从文本文件中提取的字符串HTTP响应字段。最简单的方法是什么?我可以使用BaseHTTPServer解析请求,但无法找到响应的内容 我的回答非常标准,格式如下 HTTP/1.1 200 OK Date: Thu, Jul 3 15:27:54 2014 Content-Type: text/xml; charset="utf-8" Connection: close Content-Length: 626 提前感谢, 您可能需要考虑使用Python请
HTTP/1.1 200 OK
Date: Thu, Jul 3 15:27:54 2014
Content-Type: text/xml; charset="utf-8"
Connection: close
Content-Length: 626
提前感谢,
您可能需要考虑使用Python请求。 链接: 这里有一个来自中国的例子 考虑到您的响应符合HTTP RFC 这看起来像你想做的事情吗>>> import requests
>>> url = 'http://example.test/'
>>> response = requests.get(url)
>>> response.status_code
200
>>> response.headers['content-type']
'text/html; charset=utf-8'
>>> response.content
u'Hello, world!'
您可能会发现这很有用,但请记住,这并不是为了“由用户直接实例化”而设计的 还要注意,响应字符串中的content-length标头可能不再有效(这取决于您如何获得这些响应),这只是意味着对HTTPResponse.read()的调用需要具有大于内容的值才能获得所有响应 在Python2中,它可以这样运行
from httplib import HTTPResponse
from StringIO import StringIO
http_response_str = """HTTP/1.1 200 OK
Date: Thu, Jul 3 15:27:54 2014
Content-Type: text/xml; charset="utf-8"
Connection: close
Content-Length: 626"""
class FakeSocket():
def __init__(self, response_str):
self._file = StringIO(response_str)
def makefile(self, *args, **kwargs):
return self._file
source = FakeSocket(http_response_str)
response = HTTPResponse(source)
response.begin()
print "status:", response.status
print "single header:", response.getheader('Content-Type')
print "content:", response.read(len(http_response_str)) # the len here will give a 'big enough' value to read the whole content
在Python3中,HTTPResponse
是从http.client
导入的,需要对要解析的响应进行字节编码。根据从何处获取数据,此操作可能已经完成或需要显式调用
from http.client import HTTPResponse
from io import BytesIO
http_response_str = """HTTP/1.1 200 OK
Date: Thu, Jul 3 15:27:54 2014
Content-Type: text/xml; charset="utf-8"
Connection: close
Content-Length: 626
teststring"""
http_response_bytes = http_response_str.encode()
class FakeSocket():
def __init__(self, response_bytes):
self._file = BytesIO(response_bytes)
def makefile(self, *args, **kwargs):
return self._file
source = FakeSocket(http_response_bytes)
response = HTTPResponse(source)
response.begin()
print( "status:", response.status)
# status: 200
print( "single header:", response.getheader('Content-Type'))
# single header: text/xml; charset="utf-8"
print( "content:", response.read(len(http_response_str)))
# content: b'teststring'
这看起来确实像我需要的技巧。我可能可以通过使用正则表达式来完成我的简单任务,但是使用HTTPResponse感觉更正确。非常感谢。作为一个跟进,测试和是的,这是我想要的。但如果有一个保持活力的连接呢?我们可以使用此解决方案解析多个头/体吗?类似于这个未回答问题的示例:对于python3,您可以使用http.client import HTTPResponse中的
,
有人使用python3实现了这一点吗?我得到了TypeError:decoding str不受支持
at文件/usr/lib/python3.6/http/client.py”,第258行,in_read\u status line=str(self.fp.readline(_MAXLINE+1),“iso-8859-1”)
这是如何回答这个问题的?如何将已经存在的响应字符串加载到其中?这是一个不相关的答案。问题是关于解析已经存在的完整响应字符串而不是请求本身。