Python 套接字数据返回 <byte> 对象。如何正则表达式它?

标签 python proxy sockets http-headers python-3.x

我正在用 python (3) 编写一个基本的 html 代理,到目前为止我还没有使用像 http.server 这样的预构建类。

我刚刚启动一个接受连接的套接字:

self.listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.listen_socket.bind((socket.gethostname(), 4321))
self.listen_socket.listen(5)
(a, b) = self.listen_socket.accept()
content = a.recv(100000)

现在内容存储如下数据:

b'GET http://www.google.com/firefox HTTP/1.1\r\nHost: www.google.com\r\nUser-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2) Gecko/20100207 Namoroka/3.6\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nAccept-Language: en-us,en;q=0.5\r\nAccept-Encoding: gzip,deflate\r\nAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\nKeep-Alive: 115\r\nProxy-Connection: keep-alive\r\nCookie: PREF=ID=1ac935f4d893f655:U=73a4849dc5fc23a4:TM=1266851688:LM=1267023171:S=Log1PmXRMlNjX3Of; NID=32=EnrZjTqILuW2_aMLtgsJ96FdEMF3s5FoMJSVq9GMr9dhLhTAd3F5RcQ3ImyVBiO2eYNKKMhzlGg7r8zXmeSq50EigS5sdKtCL9BMHpgCxZazA2NiyB0bTRWhp8-0BObn\r\n\r\n'

我怎样才能正则表达式它?转换为字符串对我来说不起作用。

或者,最终,我需要找出所查询的地址,例如本例中的http://www.google.com/firefox。有我不知道的解析器吗?我怎样才能达到结果?

提前致谢。

最佳答案

转换为字符串时需要包含编码,例如使用:

>>> str(b'GET http://...', 'UTF-8')
'GET http://...'

如果您不使用编码,那么正如您发现的那样,您会得到一些不太有用的东西:

>>> str(b'GET http://...')
"b'GET http://...'"

关于Python 套接字数据返回 <byte> 对象。如何正则表达式它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2341972/

相关文章:

python - 如何使用 Liblas 模块填充 liblas.point.Point 对象?

python - 是什么导致了这个程序的错误

带代理的 SSL (https)

连接功能时常失效?

perl - 为什么 Perl 的 IO::Socket::SSL->new() 失败?

java - 通过可序列化的套接字传输对象

python - xcopy python 部署

node.js - APache2 反向代理背后的 NodeJS 应用程序在上传文件时出现错误 "413 Request Entity Too Large"

macos - OSX : Why does curl not use Automatic Proxy Configuration/PAC?

ffmpeg - 重新着色图像