栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 面试经验 > 面试问答

python parse http响应(字符串)

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python parse http响应(字符串)

您可能会发现这很有用,请记住HTTPResponse并非旨在“由用户直接实例化”。

还要注意,响应字符串中的content-
length标头可能不再有效(取决于您获取这些响应的方式),这仅意味着对HTTPResponse.read()的调用需要具有大于内容的值为了得到一切。

在python 2中,可以这种方式运行。

from httplib import HTTPResponsefrom StringIO import StringIOhttp_response_str = """HTTP/1.1 200 OKDate: Thu, Jul  3 15:27:54 2014Content-Type: text/xml; charset="utf-8"Connection: closeContent-Length: 626"""class FakeSocket():    def __init__(self, response_str):        self._file = StringIO(response_str)    def makefile(self, *args, **kwargs):        return self._filesource = FakeSocket(http_response_str)response = HTTPResponse(source)response.begin()print "status:", response.statusprint "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

在python
3中,

HTTPResponse
从中导入
http.client
,并且要解析的响应需要进行字节编码。根据从何处获取数据,可能已经完成或需要显式调用

from http.client import HTTPResponsefrom io import BytesIOhttp_response_str = """HTTP/1.1 200 OKDate: Thu, Jul  3 15:27:54 2014Content-Type: text/xml; charset="utf-8"Connection: closeContent-Length: 626teststring"""http_response_bytes = http_response_str.enpre()class FakeSocket():    def __init__(self, response_bytes):        self._file = BytesIO(response_bytes)    def makefile(self, *args, **kwargs):        return self._filesource = FakeSocket(http_response_bytes)response = HTTPResponse(source)response.begin()print( "status:", response.status)# status: 200print( "single header:", response.getheader('Content-Type'))# single header: text/xml; charset="utf-8"print( "content:", response.read(len(http_response_str)))# content: b'teststring'


转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/640271.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号