2014-07-14 4 views
9

파이썬 2.7을 사용하고 있으며 이미 텍스트 파일에서 추출한 문자열 HTTP 응답 필드를 구문 분석하려고합니다. 가장 쉬운 방법은 무엇입니까? BaseHTTPServer를 사용하여 요청을 구문 분석 할 수 있지만 응답을 찾을 수 없습니다. 내가 가진python parse http 응답 (문자열)

응답은 사전에

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 

덕분에 꽤 표준 다음과 같은 형식으로되어 있습니다

답변

16

당신은 HTTPResponse이되도록 설계되지 않았 음을 명심,이 유용한를 찾을 수 있습니다 "사용자가 직접 인스턴스화."

응답 문자열의 content-length 헤더가 더 이상 유효하지 않을 수도 있습니다 (이 응답을 얻은 방법에 따라 다름) 이는 HTTPResponse.read()에 대한 호출이 value 모든 것을 얻으려면 콘텐츠보다 커야합니다.

이 예제는 Python v2에만 해당되며 v3-ish에서는 StringIO 및 httplib의 가져 오기 위치가 변경되었습니다.

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 
+0

이것은 정말로 내가 필요한 트릭처럼 보입니다. 아마 내 간단한 목적을 위해 regexes를 사용하여 내 길을 일할 수 있지만 HTTPResponse를 사용하면 훨씬 더 정확하다고 느낀다. 매우 감사합니다. –

+1

후속 조치로서 테스트를 거쳤으며 그렇습니다. 이는 내가 원하는 것을 수행합니다. –

+0

하지만 연결이 지속되면 어떻게 될까요? 이 솔루션을 사용하여 여러 헤더/본문을 파싱 할 수 있습니까? 이 대답하지 않은 질문의 예와 같은 것 : http://stackoverflow.com/questions/34786880/multiple-response-parsing-in-python?lq=1 – sajjadG

3

당신은 파이썬 요청을 사용하여 고려할 수 있습니다.

링크 : 다음

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!' 
+3

이 질문에 어떻게 대답합니까? – saaj

+0

기존 응답 문자열을 어떻게로드합니까? – luckydonald