python正則匹配URL
阿新 • • 發佈:2018-12-22
正則匹配URL過程
- 獲得http請求頭的字串列表
- 正則匹配列表的第二個元素
- 判斷正則匹配結果
正則匹配url_demo
import re def main(): name = """ GET / HTTP/1.1 Host: 127.0.0.1:9999 Connection: keep-alive Cache-Control: max-age=0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0 .8 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Geck o) Chrome/50.0.2661.102 Safari/537.36 Accept-Encoding: gzip, deflate, sdch Accept-Language: zh-CN,zh;q=0.8 GET /favicon.ico HTTP/1.1 Host: 127.0.0.1:9999 Connection: keep-alive User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Geck o) Chrome/50.0.2661.102 Safari/537.36 Accept: */* Referer: http://127.0.0.1:9999/ Accept-Encoding: gzip, deflate, sdch Accept-Language: zh-CN,zh;q=0.8 """ # str.splitlines([keepends]) # http://www.runoob.com/python3/python3-string-splitlines.html # keepends -- 在輸出結果裡是否去掉換行符('\r', '\r\n', \n'),預設為 False,不包含換行符,如果為 True,則保留換行符。 # str1 = name.splitlines(True) # print("保留換行符結果:\n",str1) str2 = name.splitlines(False) # print("不保留換行符結果:\n",str2) url_name = re.match(r"[^/]+(/[^ ]*)",str2[1]) if url_name: url_name = url_name.group(1) print("正則匹配到的結果是:",url_name) else: print("未成功匹配到資料") if __name__ == '__main__': main()
執行結果
可以匹配到我們需要的url