python3 url 获取域名ip

您所在的位置:网站首页 通过域名查询ip地址和端口 python3 url 获取域名ip

python3 url 获取域名ip

2024-07-01 20:00| 来源: 网络整理| 查看: 265

从url中提取域名

方法一:

In [1]: from urllib import parse In [2]: url = 'https://www.jianshu.com/writer#/notebooks/30425954/notes/43737977' In [3]: parse.urlparse(url).hostname Out[3]: 'www.jianshu.com'

这种方法为从urlparse模块中通过urlparse方法提取url通过hostname属性获取当前url的域名。

方法二:

In [10]: import urllib In [11]: proto, rest = urllib.splittype(url) In [12]: host, rest = urllib.splithost(rest) In [13]: host Out[13]: 'www.jianshu.com'

此方法是通过urllib模块中splittype方法先从url中获取到proto协议及rest结果,然后通过splithost从rest中获取到host及rest结果,此时host为域名。(rest被分割了两次)如下图:

 

从域名中提取ip

方法一:

In [14]: from socket import gethostbyname In [15]: ip_list = gethostbyname('www.jianshu.com') In [16]: ip_list Out[16]: '119.167.250.231'

此方法为从sokcet模块中获取到gethostbyname方法将域名传递进去就能解析出域名的ip。

方法二:

>>> import os >>> lines=os.popen('nslookup blog.csdn.net 221.130.33.52') >>> row=lines.readlines() >>> row ['Server:\t\t221.130.33.52\n', 'Address:\t221.130.33.52#53\n', '\n', 'Non-authoritative answer:\n', 'Name:\tblog.csdn.net\n', 'Address: 47.95.47.253\n', '\n'] >>> if len(row) > 5: ... for ip in row[5:]: ... if 'Address:' in ip: ... ip=ip.split(':')[1].strip() ... print ip ... 47.95.47.253

此方法为通过nslookup获取域名的ip。

注意:

以上从域名中提取ip会不准确,需要设置DNS服务器,这样解析域名就准确了。

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3