从http请求中分离URL

2024-10-01 07:14:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我在学习Python语言。我想知道如何拆分HTTP请求

GET /en/html/dummy.php?name=MyName&married=not+single &male=yes HTTP/1.1

Host: www.explainth.at
User-Agent: Mozilla/5.0 (Windows;en-GB; rv:1.8.0.11) Gecko/20070312 Firefox/1.5.0.11
Accept: text/xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://www.explainth.at/en/misc/httpreq.shtml

我想结合部分后,得到和主机(粗体字母)。。你知道吗

获取/en/html/dummy.php?name=MyName&;married=not+单身&;male=yesHTTP/1.1

主持人:www.explainth.at

如何做到这一点?你知道吗


Tags: textnamehttphtmlwwwnotmaleat
2条回答

不清楚您为什么要这样做,上下文或目标是什么,或者这些数据是如何到达您的程序的。但是,Python在其字符串类型上支持许多有用的字符串操作。因此,如果您有一个包含所有这些文本的字符串,那么您可能会发现splitlines方法很有用,同时还有一些列表切片:

s = """\ ... GET /en/html/dummy.php?name=MyName&married=not+single &male=yes HTTP/1.1 ... Host: www.explainth.at ... User-Agent: Mozilla/5.0 (Windows;en-GB; rv:1.8.0.11) Gecko/20070312 Firefox/1.5.0.11 ... Accept: text/xml,text/html;q=0.9,text/plain;q=0.8,image/png,/;q=0.5 ... """ s.splitlines()[:2] ['GET /en/html/dummy.php?name=MyName&married=not+single &male=yes HTTP/1.1', 'Host: www.explainth.at']

当然,如果您正在编写任何一种真正的HTTP服务器软件,这可能不是正确的方法(在这样低的级别上操作几乎没有理由,如果您需要,您几乎肯定希望编写或重新使用真正的HTTP解析器)。所以你可能想问一个更精确的问题。你知道吗

必须按\r\n字节分割HTTP请求。(windows上的换行标记)

相关问题 更多 >