python如何進行高效的域名解析


title: python如何進行高效的域名解析
date: 2019-06-18 10:55:57
tags:

  • python
  • tldextract
  • urllib
    categories:
  • 開發(fā)
  • 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: 使用何種協(xié)議
    netloc: 網(wǎng)絡(luò)地址,解析出來是帶ip的
    path: 分層路徑
    params: 參數(shù)
    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']}

等等。更多詳情: 標準庫

如果我們?nèi)〕銎溆蛎刂?,如何做?/p>

比如: 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))

參考來源

如果使用以上代碼的話,那么我們需要將現(xiàn)有的所有域名服務(wù)器都枚舉出來,收集起來比較麻煩。

所以我們可以再github尋找第三方python庫的支持,不重復(fù)造輪子。

接下來,則是python第三方庫tldextract的使用。

tldextract的使用

安裝

pip install tldextract
# 直接運行命令行
tldextract http://focums.foo.com.cn
# 得出
focums foo com.cn

但是在內(nèi)網(wǎng)環(huán)境下運行命令,則爆出SocketTimeout錯誤,所以可以得知,其進行了網(wǎng)絡(luò)請求,然后再進行我們域名的解析。

錯誤詳情:

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網(wǎng)站之后,然后獲取到域名列表,再對我們提供的域名進行解析返回。

官方提供了緩存機制:

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'

這樣我們就可以將提出爬蟲中獲取的子域內(nèi)容了。

如果是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]: ''

以上。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容