Python编程系列---获取请求报文行中的URL的几种方法总结

时间:2024-04-04 16:36:03

在浏览器访问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方法

 import re

 request = """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
""" # 将上面的请求报文以行的形式分割返回一个列表
request_lines = request.splitlines() # 方法一:使用正则表达式中的match方法
# [^/]+ 不以/开头的至少一个字符 匹配到/之前
# (/[^ ]*) 以分组来匹配第一个字符是/,然后不以空格开始的0到多个字符,也就是空格之前
# 最后通过匹配可以拿到 请求的路径名 比如:index.html ret = re.match(r"[^/]+(/[^ ]*)", request_lines[0])
print("使用正则表达式中的match方法结果为:",ret.group(1)) 结果如下:
使用正则表达式中的match方法结果为: /index.html Process finished with exit code 0

方法二:使用正则表达式中的spilt方法

 import re

 1 request = """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
""" # 将上面的请求报文以行的形式分割返回一个列表
request_lines = request.splitlines() # 方法二:使用正则表达式中的spilt方法
ret2 = re.split(" ",request_lines[0])
print("使用正则表达式中的spilt方法的结果为:",ret2[1]) 结果如下:
使用正则表达式中的spilt方法的结果为: /index.html Process finished with exit code 0

方法三:使用字符串分割的方法

 request = """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
""" # 将上面的请求报文以行的形式分割返回一个列表
request_lines = request.splitlines() # 方法三:使用字符串分割的方法
str = request_lines[0].split() # 或者.spilt(" ",2)
url_str = str[1]
print("使用字符串spilt分割的方法:",url_str) 结果如下:
使用字符串spilt分割的方法: /index.html Process finished with exit code 0

如果你和我有共同爱好,我们可以加个好友一起交流哈!

Python编程系列---获取请求报文行中的URL的几种方法总结