나는 http://www.techcrunch.com/과 같은 링크가 있으며 링크의 techcrunch.com 부분 만 얻고 싶습니다. 파이썬으로 어떻게 할 수 있습니까?링크의 루트 도메인 가져 오기
답변
호스트 이름을 얻는 것은 충분히 urlparse을 사용하여 쉽게 : "루트 도메인"그러나 더 문제가 될 것입니다 얻기
hostname = urlparse.urlparse("http://www.techcrunch.com/").hostname
, 그것이 통 사적 의미에서 정의되지 않기 때문에. "www.theregister.co.uk"의 루트 도메인은 무엇입니까? 기본 도메인을 사용하는 네트워크는 어떻습니까? "devbox12"는 유효한 호스트 이름이 될 수 있습니다. 이 처리하는
한 가지 방법은 입니다뿐만 아니라 개인 도메인 (".NET", ".ORG"예 ".COM") 실제 최상위 도메인 모두를 카탈로그 시도 Public Suffix List을 사용하는 것입니다 TLD와 같이을 사용하십시오 (예 : ".co.uk"또는 ".github.io"). 당신은 publicsuffix2 라이브러리를 사용하여 파이썬에서 PSL에 액세스 할 수 있습니다 : 이것은 내 목적을 위해 일한
import publicsuffix
import urlparse
def get_base_domain(url):
# This causes an HTTP request; if your script is running more than,
# say, once a day, you'd want to cache it yourself. Make sure you
# update frequently, though!
psl = publicsuffix.fetch()
hostname = urlparse.urlparse(url).hostname
return publicsuffix.get_public_suffix(hostname, psl)
이 코드의 호스트 이름 = ".". join (len (호스트 이름 [-2]) <4 및 호스트 이름 [-3 :] 또는 호스트 이름 [-2 :]) 작동합니까? Thanks – Joozty
@Joozty - 부정적 인덱스는 마지막부터 시작하므로'hostname [-2]'는 마지막 항목 (이 경우 점으로 구분 된 호스트 이름)의 마지막 항목을 의미합니다. 'foo와 bar 또는 baz'는 삼항처럼 작동합니다 : "foo"가 참이면 "bar"를 반환하십시오; 그렇지 않으면 "baz"를 반환합니다. 마지막으로,'hostname [-3 :]'는 마지막 세 부분을 의미합니다. 모두 함께, 이것은 "호스트 이름의 마지막 부분이 4 자보다 짧으면 마지막 세 부분을 사용하여 점으로 결합합니다. 그렇지 않으면 마지막 두 부분 만 가져 와서 함께 결합하십시오." –
어떤 이유로 모듈을 설치 한 후에도 Python 3에서'ImportError : get_public_suffix '이름을 가져올 수 없습니다. 어떤 답변도 온라인이나 문서에서 찾을 수 없으므로 대신 그냥 "tldextract"를 사용하십시오! 물론, 나는'sudo pip3 install tldextract'를 먼저해야만했다. – Nagev
. 나는 그것을 나눌 것이라고 생각했다.
".".join("www.sun.google.com".split(".")[-2:])
"www.sun.google.co.uk"테스트는 어떻습니까? "google.co.uk"대신 "co.uk"이 표시됩니다 ... 건배! –
예, Ben Blank의 접근 방식을 사용하십시오. 내가 2010 년에 생각한 것이 확실하지 않음 :-) –
______Using 파이썬 3.3 아니라 2.x는 ________
나는 벤 빈의 대답에 작은 일을 추가하고 싶습니다.
from urllib.parse import quote,unquote,urlparse
u=unquote(u) #u= URL e.g. http://twitter.co.uk/hello/there
g=urlparse(u)
u=g.netloc
지금까지 도메인 이름은 urlparse입니다.
어떤 것이 최상위 도메인인지 알아야하는 하위 도메인을 제거하려면 삭제해야합니다. 예 : 위의 http://twitter.co.uk
-co.uk
은 TLD로 http://sub.twitter.com
에는 TLD로 .com
이고 서브 도메인은 sub
입니다.
그래서 우리는 모두 tlds 인 파일/목록을 가져와야합니다.
tlds = load_file("tlds.txt") #tlds holds the list of tlds
hostname = u.split(".")
if len(hostname)>2:
if hostname[-2].upper() in tlds:
hostname=".".join(hostname[-3:])
else:
hostname=".".join(hostname[-2:])
else:
hostname=".".join(hostname[-2:])
URL의
일반적인 구조 :
scheme://netloc/path;parameters?query#fragment
TIMTOWTDI 모토 으로 : urlparse를 사용
,
귀하의 경우3210>>> from urllib.parse import urlparse # python 3.x
>>> parsed_uri = urlparse('http://www.stackoverflow.com/questions/41899120/whatever') # returns six components
>>> domain = '{uri.netloc}/'.format(uri=parsed_uri)
>>> result = domain.replace('www.', '') # as per your case
>>> print(result)
'stackoverflow.com/'
tldextract를 사용
>>> import tldextract # The module looks up TLDs in the Public Suffix List, mantained by Mozilla volunteers
>>> tldextract.extract('http://forums.news.cnn.com/')
ExtractResult(subdomain='forums.news', domain='cnn', suffix='com')
:
>>> extracted = tldextract.extract('http://www.techcrunch.com/')
>>> '{}.{}'.format(extracted.domain, extracted.suffix)
'techcrunch.com'
tldextract
on the other hand knows what all gTLDs [Generic Top-Level Domains] and ccTLDs [Country Code Top-Level Domains] look like by looking up the currently living ones according to the Public Suffix List. So, given a URL, it knows its subdomain from its domain, and its domain from its country code.
힘내라!:)
다음 스크립트는 완벽하지는 않지만 표시/단축 목적으로 사용할 수 있습니다. 타사 종속성을 피하고 싶다면/특히 원격으로 데이터를 가져 와서 캐싱해야 할 경우 프로젝트에서 사용하는 스크립트를 따르십시오. 가장 일반적인 도메인 확장을 위해 도메인의 마지막 두 부분을 사용하고 덜 알려진 도메인 확장의 나머지 부분에 대해 마지막 세 부분을 남깁니다.
from urlparse import urlparse
def extract_domain(url):
parsed_domain = urlparse(url)
domain = parsed_domain.netloc or parsed_domain.path # Just in case, for urls without scheme
domain_parts = domain.split('.')
if len(domain_parts) > 2:
return '.'.join(domain_parts[-(2 if domain_parts[-1] in {
'com', 'net', 'org', 'io', 'ly', 'me', 'sh', 'fm', 'us'} else 3):])
return domain
extract_domain('google.com') # google.com
extract_domain('www.google.com') # google.com
extract_domain('sub.sub2.google.com') # google.com
extract_domain('google.co.uk') # google.co.uk
extract_domain('sub.google.co.uk') # google.co.uk
extract_domain('www.google.com') # google.com
extract_domain('sub.sub2.voila.fr') # sub2.voila.fr
def get_domain(url):
u = urlsplit(url)
return u.netloc
def get_top_domain(url):
u"""
>>> get_top_domain('http://www.google.com')
'google.com'
>>> get_top_domain('http://www.sina.com.cn')
'sina.com.cn'
>>> get_top_domain('http://bbc.co.uk')
'bbc.co.uk'
>>> get_top_domain('http://mail.cs.buaa.edu.cn')
'buaa.edu.cn'
"""
domain = get_domain(url)
domain_parts = domain.split('.')
if len(domain_parts) < 2:
return domain
top_domain_parts = 2
# if a domain's last part is 2 letter long, it must be country name
if len(domain_parts[-1]) == 2:
if domain_parts[-1] in ['uk', 'jp']:
if domain_parts[-2] in ['co', 'ac', 'me', 'gov', 'org', 'net']:
top_domain_parts = 3
else:
if domain_parts[-2] in ['com', 'org', 'net', 'edu', 'gov']:
top_domain_parts = 3
return '.'.join(domain_parts[-top_domain_parts:])
- 1. AS3에서 도메인 가져 오기
- 2. IFrame 도메인 가져 오기?
- 3. Ajax 요청이오고있는 도메인 가져 오기
- 4. drupal보기에서 루트 분류 이름 가져 오기
- 5. 루트 컨테이너에서 TreeViewItem 데이터 액세스 가져 오기
- 6. 루트 디렉토리에있는 폴더에서 디렉토리 가져 오기 PHP
- 7. 문제 PHP에서 루트 URL 가져 오기
- 8. Django : 신호에서 현재 도메인 (http_host) 가져 오기
- 9. 도메인 \ 별칭 콤보에서 표시 이름 가져 오기
- 10. PHP를 사용하여 API 호출에서 도메인 가져 오기?
- 11. URL에서 하위 도메인없이 도메인 가져 오기
- 12. JS/JQuery에서 교차 도메인 가져 오기 요청
- 13. Grails 도메인 클래스로 XML 가져 오기
- 14. VB6 Active Directory 도메인 목록 가져 오기
- 15. 정지 하위 도메인 액세스 루트
- 16. 도메인 기반 디자인 - 집계 루트
- 17. 도메인 기반 디자인 - 저장소 및 집계 루트
- 18. 도메인 기반 디자인 : 루트 당 집계
- 19. GORM : User (루트 객체)에 속한 모든 도메인 인스턴스를 나열하십시오.
- 20. simplexml을 사용하여 XML doc의 루트 노드 가져 오기
- 21. 스프링 컨트롤러에서 웹 응용 프로그램 루트 가져 오기
- 22. CRM 4 rdl 오류 가져 오기 루트 요소가 없습니다.
- 23. NSString 또는 NSURL에서 웹 사이트 루트 가져 오기
- 24. Cling에있는 모든 DLNA 루트 스토리지 디렉토리 가져 오기?
- 25. 가져 오기 배열 가져 오기
- 26. 여러 개의 하위 도메인 - 같은 루트 디렉토리
- 27. 도메인 기반 디자인의 루트 집계 문제
- 28. Java에서 FQDN 가져 오기
- 29. jquery를 사용하여 이미지 링크의 'src'를 가져 옵니까?
- 30. 모달 상자를 만든 링크의 ID를 가져 옵니까?
이 트릭을 할 수 있습니다 최악의 경우 시나리오 도메인 대신 두 세 부분이있을 것이다. http://docs.python.org/library/urlparse.html – Eli