在瀏覽器訪問web服務器的時候,服務器收到的是一個請求報文,大概GET請求的格式大概如下:
先隨便拿到一個請求報文,藍色即為我們要獲取的
GET /index.html HTTP/1.1
Host: www.baidu.com
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3528.4 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8
方法一:使用正則表達式中的match方法
1 import re 2
3 request = """GET /index.html HTTP/1.1 4 Host: www.baidu.com 5 Connection: keep-alive 6 Cache-Control: max-age=0 7 Upgrade-Insecure-Requests: 1 8 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3528.4 Safari/537.36 9 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 10 Accept-Encoding: gzip, deflate, br 11 Accept-Language: zh-CN,zh;q=0.9,en;q=0.8 12 """
13
14 # 將上面的請求報文以行的形式分割返回一個列表
15 request_lines = request.splitlines() 16
17 # 方法一:使用正則表達式中的match方法
18 # [^/]+ 不以/開頭的至少一個字符 匹配到/之前
19 # (/[^ ]*) 以分組來匹配第一個字符是/,然后不以空格開始的0到多個字符,也就是空格之前
20 # 最后通過匹配可以拿到 請求的路徑名 比如:index.html
21
22 ret = re.match(r"[^/]+(/[^ ]*)", request_lines[0]) 23 print("使用正則表達式中的match方法結果為:",ret.group(1)) 24
25
26 結果如下: 27 使用正則表達式中的match方法結果為: /index.html 28
29 Process finished with exit code 0
方法二:使用正則表達式中的spilt方法
import re
1 request = """GET /index.html HTTP/1.1 2 Host: www.baidu.com 3 Connection: keep-alive 4 Cache-Control: max-age=0 5 Upgrade-Insecure-Requests: 1 6 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3528.4 Safari/537.36 7 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 8 Accept-Encoding: gzip, deflate, br 9 Accept-Language: zh-CN,zh;q=0.9,en;q=0.8 10 """
11
12 # 將上面的請求報文以行的形式分割返回一個列表
13 request_lines = request.splitlines() 14
15 # 方法二:使用正則表達式中的spilt方法
16 ret2 = re.split(" ",request_lines[0]) 17 print("使用正則表達式中的spilt方法的結果為:",ret2[1]) 18
19
20 結果如下: 21 使用正則表達式中的spilt方法的結果為: /index.html 22
23 Process finished with exit code 0
方法三:使用字符串分割的方法
1 request = """GET /index.html HTTP/1.1 2 Host: www.baidu.com 3 Connection: keep-alive 4 Cache-Control: max-age=0 5 Upgrade-Insecure-Requests: 1 6 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3528.4 Safari/537.36 7 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 8 Accept-Encoding: gzip, deflate, br 9 Accept-Language: zh-CN,zh;q=0.9,en;q=0.8 10 """
11
12 # 將上面的請求報文以行的形式分割返回一個列表
13 request_lines = request.splitlines() 14
15 # 方法三:使用字符串分割的方法
16 str = request_lines[0].split() # 或者.spilt(" ",2)
17 url_str = str[1] 18 print("使用字符串spilt分割的方法:",url_str) 19
20
21
22 結果如下: 23 使用字符串spilt分割的方法: /index.html 24
25 Process finished with exit code 0
如果你和我有共同愛好,我們可以加個好友一起交流哈!