好久不更新了,今天给大家带来两种提取url中域名、从域名中获取ip的方法供大家学习。如果你觉得我的文章有用,别忘给我点亮小红心和关注作者哦。
python从url中提取域名
方法一:
In [1]: from urlparse import urlparse
In [2]: url = 'https://www.jianshu.com/writer#/notebooks/30425954/notes/43737977'
In [3]: 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被分割了两次)如下图:

python从域名中提取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服务器,这样解析域名就准确了。
网友评论