簡體   English   中英

python解析http響應(字符串)

[英]python parse http response (string)

我正在使用 python 2.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

提前致謝,

您可能會發現這很有用,請記住HTTPResponse並非旨在“由用戶直接實例化”。

另請注意,響應字符串中的內容長度標頭可能不再有效(這取決於您如何獲取這些響應)這僅意味着對 HTTPResponse.read() 的調用需要具有大於內容的值為了得到這一切。

在python 2中,它可以這樣運行。

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

在python 3中, 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'

您可能需要考慮使用 python-requests。

鏈接: http : //docs.python-requests.org/en/latest/

這是來自http://dancallahan.info/journal/python-requests/的示例

考慮到您的響應符合 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!'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM