[英]How to parse HTTP raw bytes and get the HTTP content in python?
我使用scapy嗅探一些数据包,并得到一些HTTP响应数据包,这些数据包是我无法解析的字节,例如:
b'HTTP/1.1 200 OK\r\nDate: Thu, 07 Dec 2017 02:44:18 GMT\r\nServer:Apache/2.4.18 (Ubuntu)\r\nLast-Modified: Tue, 14 Nov 2017 05:51:36 GMT\r\nETag: "2c39-55deafadf0ac0-gzip"\r\nAccept-Ranges: bytes\r\nVary: Accept-Encoding\r\nContent-Encoding: gzip\r\nContent-Length: 3186\r\nConnection: close\r\nContent-Type: text/html\r\n\r\n\x1f\x8b'
有没有办法获取此字节数组的内容部分,以便可以使用gzip库进行解码? 我不想使用request
来获取HTTP响应,因为我只想处理我拥有的原始数据包。
没有内置的方法可以解析这样的原始HTTP响应并正确处理压缩。 我会使用urllib3
:
import urllib3
from io import BytesIO
from http.client import HTTPResponse
class BytesIOSocket:
def __init__(self, content):
self.handle = BytesIO(content)
def makefile(self, mode):
return self.handle
def response_from_bytes(data):
sock = BytesIOSocket(data)
response = HTTPResponse(sock)
response.begin()
return urllib3.HTTPResponse.from_httplib(response)
if __name__ == '__main__':
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('httpbin.org', 80))
sock.send(b'GET /gzip HTTP/1.1\r\nHost: httpbin.org\r\n\r\n')
raw_response = sock.recv(8192)
response = response_from_bytes(raw_response)
print(response.headers)
print(response.data)
您可以使用以下方法提取字节的值部分
response_bytes.decode('utf-8')
然后,您可以使用Beautiful Soup解析返回的信息以获取所需的任何部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.