title: python如何进行高效的域名解析
date: 2019-06-18 10:55:57
tags:
- python
- tldextract
- urllib
categories: - 开发
- python
- 第三方库
- tldextract
python如何进行高效的域名解析
python使用标准库进行域名解析
使用urllib.parse进行域名解析:
In [7]: from urllib import parse
In [16]: url = 'http://focus.foo.com.cn:80/get_params?a=bbb&c=ccc'
In [17]: after_parse = parse.urlparse(url)
In [18]: after_parse
Out[18]: ParseResult(scheme='http', netloc='focus.foo.com.cn:80', path='/get_params', params='', query='a=bbb&c=ccc', fragment='')
"""
scheme: 使用何种协议
netloc: 网络地址,解析出来是带ip的
path: 分层路径
params: 参数
query: 查询组件
"""
如何需要取出主域名那么可以使用:
In [20]: host, port = parse.splitport(after_parse.netloc)
In [21]: host, port
Out[21]: ('focus.foo.com.cn', '80')
如何将需要将query返回为字典类型:
In [23]: parse.parse_qs(after_parse.query)
Out[23]: {'a': ['bbb'], 'c': ['ccc']}
等等。更多详情: 标准库
如果我们取出其域名地址,如何做?
比如: http://focus.foo.com.cn:80/
取出: foo.com.cn;
取得域名地址 python代码
#!-*- coding:utf-8 -*-
from urllib.parse import urlparse
def get_domain_by_url(url):
domain_config = ['com', 'top', 'xyz', 'cx', 'red', 'net', 'cn', 'org', 'edu']
o = urlparse(url)
host = o.netloc
host = host.split('.')
host.reverse()
res = []
for i in range(len(host)):
if host[i] in domain_config:
res.append(host[i])
else:
res.append(host[i])
break
res.reverse()
domain = '.'.join(res)
return domain
url = "https://www.wx.qq.com.cn";
print(get_domain_by_url(url))
如果使用以上代码的话,那么我们需要将现有的所有域名服务器都枚举出来,收集起来比较麻烦。
所以我们可以再github寻找第三方python库的支持,不重复造轮子。
接下来,则是python第三方库tldextract的使用。
tldextract的使用
安装
pip install tldextract
# 直接运行命令行
tldextract http://focums.foo.com.cn
# 得出
focums foo com.cn
但是在内网环境下运行命令,则爆出SocketTimeout错误,所以可以得知,其进行了网络请求,然后再进行我们域名的解析。
错误详情:
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='publicsuffix.org', port=443): Max retries exceeded with url: /list/public_suffix_list.dat (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f06384d29b0>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)
所以其一定是先请求了pulicsuffix.org网站之后,然后获取到域名列表,再对我们提供的域名进行解析返回。
官方提供了缓存机制:
env TLDEXTRACT_CACHE="~/tldextract.cache" tldextract --update
将我们从远程获取的列表存入到~/tldextract.cache中。
在代码中使用:
In [1]: from tldextract import TLDExtract
In [2]: extract = TLDExtract(cache_file='/root/tldextract.cache')
In [3]: extract('http://forums.bbc.co.uk') # 解析url
Out[3]: ExtractResult(subdomain='forums', domain='bbc', suffix='co.uk')
In [4]: after = extract('http://forums.bbc.co.uk')
In [5]: after.registered_domain # 获取注册域名
Out[5]: 'bbc.co.uk'
这样我们就可以将提出爬虫中获取的子域内容了。
如果是ip如何解析?
In [6]: after = extract('http://127.0.0.1:8080/deployed/')
In [7]: after
Out[7]: ExtractResult(subdomain='', domain='127.0.0.1', suffix='')
In [8]: after.registered_domain
Out[8]: ''
以上。