Sử dụng this file of effective tlds mà someone else tìm thấy trên trang web của Mozilla:
from __future__ import with_statement
from urlparse import urlparse
# load tlds, ignore comments and empty lines:
with open("effective_tld_names.dat.txt") as tld_file:
tlds = [line.strip() for line in tld_file if line[0] not in "/\n"]
def get_domain(url, tlds):
url_elements = urlparse(url)[1].split('.')
# url_elements = ["abcde","co","uk"]
for i in range(-len(url_elements), 0):
last_i_elements = url_elements[i:]
# i=-3: ["abcde","co","uk"]
# i=-2: ["co","uk"]
# i=-1: ["uk"] etc
candidate = ".".join(last_i_elements) # abcde.co.uk, co.uk, uk
wildcard_candidate = ".".join(["*"] + last_i_elements[1:]) # *.co.uk, *.uk, *
exception_candidate = "!" + candidate
# match tlds:
if (exception_candidate in tlds):
return ".".join(url_elements[i:])
if (candidate in tlds or wildcard_candidate in tlds):
return ".".join(url_elements[i-1:])
# returns "abcde.co.uk"
raise ValueError("Domain not in global list of TLDs")
print get_domain("http://abcde.co.uk", tlds)
kết quả trong:
abcde.co.uk
Tôi đánh giá cao nó nếu ai đó cho tôi biết mà bit của trên có thể được viết lại theo một cách pythonic hơn. Ví dụ, phải có một cách tốt hơn để lặp qua danh sách last_i_elements
, nhưng tôi không thể nghĩ ra. Tôi cũng không biết nếu ValueError
là điều tốt nhất để nâng cao. Bình luận?
Một câu hỏi có liên quan trước đây trên Stack Overflow: http://stackoverflow.com/questions/569137/how-to-get-domain-name-from-url –
1: Các "đơn giản nỗ lực" trong việc này câu hỏi hoạt động tốt cho tôi, ngay cả khi nó trớ trêu thay đã không làm việc cho tác giả. – ArtOfWarfare
Câu hỏi tương tự: http://stackoverflow.com/questions/14406300/python-urlparse-extract-domain-name-without-subdomain – user2314737