Python解析url、提取url参数、提取url数据(Python2、Python3、提取url、端口、协议、路径)
生活随笔
收集整理的這篇文章主要介紹了
Python解析url、提取url参数、提取url数据(Python2、Python3、提取url、端口、协议、路径)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Python3
from urllib.parse import urlparseurl = 'http://192.168.8.24:8161/11/12.htm' _url = urlparse(url) hostname = _url.hostname port = _url.port url_port = _url.netloc url_path = _url.path url_protocol = _url.scheme print(f'域名:{hostname}\n端口:{port}\n域名+端口:{url_port}\n域名路徑地址:{url_path}\n域名協議:{url_protocol}')結果
域名:192.168.8.24
端口:8161
域名+端口:192.168.8.24:8161
域名路徑地址:/11/12.htm
域名協議:http
實例
if __name__=="__main__":parser = argparse.ArgumentParser(description='寶塔面板數據庫未授權訪問')parser.add_argument("-r", "--rhost", dest="rhost", type=str, help="target host", required=True)parser.add_argument("-p", "--rport", dest="rport", type=int,help = "target port, default 888", default = 888)options = parser.parse_args()try:dip = options.rhost_url = urlparse(dip)# 判斷協議if _url.scheme == "":scheme = "http://"else:scheme = _url.scheme + "://"# 判斷域名if _url.hostname is None:domain = dipelse:domain = _url.hostname# 判斷端口if _url.port is None:port = options.rportelse:port = _url.porturl = scheme + domain + ":" + str(port)print(url)#check_baota(url) # POCexcept Exception as e:sys.exit(1)?
Python2
#!/usr/bin/env python # encoding: utf-8import urllibproto, rest = urllib.splittype("http://192.168.8.24:8161/11/12.htm") print(proto, rest) # ('http', '//192.168.8.24:8161/11/12.htm') host, rest = urllib.splithost(rest) print(host, rest) # ('192.168.8.24:8161', '/11/12.htm') host, port = urllib.splitport(host) if port is None:port =80 print(host, port) # ('192.168.8.24', '8161'結果
('http', '//192.168.8.24:8161/11/12.htm')
('192.168.8.24:8161', '/11/12.htm')
('192.168.8.24', '8161')
?
刪除url中參數
url = "http://forcloud.xyz/phpinfo.php?a=1&b=2" index = url.find('?') if index > 0:sURL = url[0:index] else:sURL = url print(sURL)?
總結
以上是生活随笔為你收集整理的Python解析url、提取url参数、提取url数据(Python2、Python3、提取url、端口、协议、路径)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 软件体系架构——质量属性
- 下一篇: ThinkPHP5 相关知识重点笔记