URL에서 프로토콜 + 호스트 이름 가져 오기
Django 앱에서 다음 request.META.get('HTTP_REFERER')
과 같은 URL에서 프로토콜과 함께 리퍼러에서 호스트 이름을 가져와야 합니다.
- https://docs.google.com/spreadsheet/ccc?key=blah-blah-blah-blah#gid=1
- https://stackoverflow.com/questions/1234567/blah-blah-blah-blah
- http://www.example.com
- https://www.other-domain.com/whatever/blah/blah/?v1=0&v2=blah+blah ...
나는 얻어야한다 :
- https://docs.google.com/
- https://stackoverflow.com/
- http://www.example.com
- https://www.other-domain.com/
다른 관련 질문을 살펴보고 urlparse에 대해 찾았지만 그 이후에는 속임수가 없었습니다.
>>> urlparse(request.META.get('HTTP_REFERER')).hostname
'docs.google.com'
당신은 그것을 할 수 있어야합니다 urlparse
(docs : python2 , python3 ) :
from urllib.parse import urlparse
# from urlparse import urlparse # Python 2
parsed_uri = urlparse('http://stackoverflow.com/questions/1234567/blah-blah-blah-blah' )
result = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)
print(result)
# gives
'http://stackoverflow.com/'
https://github.com/john-kurkowski/tldextract
이것은 더 장황한 urlparse 버전입니다. 도메인과 하위 도메인을 감지합니다.
그들의 문서에서 :
>>> import tldextract
>>> tldextract.extract('http://forums.news.cnn.com/')
ExtractResult(subdomain='forums.news', domain='cnn', suffix='com')
>>> tldextract.extract('http://forums.bbc.co.uk/') # United Kingdom
ExtractResult(subdomain='forums', domain='bbc', suffix='co.uk')
>>> tldextract.extract('http://www.worldbank.org.kg/') # Kyrgyzstan
ExtractResult(subdomain='www', domain='worldbank', suffix='org.kg')
ExtractResult
명명 된 튜플이므로 원하는 부분에 간단하게 액세스 할 수 있습니다.
>>> ext = tldextract.extract('http://forums.bbc.co.uk')
>>> ext.domain
'bbc'
>>> '.'.join(ext[:2]) # rejoin subdomain and domain
'forums.bbc'
urlsplit을 사용하는 Python3 :
from urllib.parse import urlsplit
url = "http://stackoverflow.com/questions/9626535/get-domain-name-from-url"
base_url = "{0.scheme}://{0.netloc}/".format(urlsplit(url))
print(base_url)
# http://stackoverflow.com/
순수한 문자열 연산 :) :
>>> url = "http://stackoverflow.com/questions/9626535/get-domain-name-from-url"
>>> url.split("//")[-1].split("/")[0].split('?')[0]
'stackoverflow.com'
>>> url = "stackoverflow.com/questions/9626535/get-domain-name-from-url"
>>> url.split("//")[-1].split("/")[0].split('?')[0]
'stackoverflow.com'
>>> url = "http://foo.bar?haha/whatever"
>>> url.split("//")[-1].split("/")[0].split('?')[0]
'foo.bar'
그게 다야 사람들.
>>> import urlparse
>>> url = 'http://stackoverflow.com/questions/1234567/blah-blah-blah-blah'
>>> urlparse.urljoin(url, '/')
'http://stackoverflow.com/'
URL이 유효하다고 생각되면 항상 작동합니다.
domain = "http://google.com".split("://")[1].split("/")[0]
다음은 약간 개선 된 버전입니다.
urls = [
"http://stackoverflow.com:8080/some/folder?test=/questions/9626535/get-domain-name-from-url",
"Stackoverflow.com:8080/some/folder?test=/questions/9626535/get-domain-name-from-url",
"http://stackoverflow.com/some/folder?test=/questions/9626535/get-domain-name-from-url",
"https://StackOverflow.com:8080?test=/questions/9626535/get-domain-name-from-url",
"stackoverflow.com?test=questions&v=get-domain-name-from-url"]
for url in urls:
spltAr = url.split("://");
i = (0,1)[len(spltAr)>1];
dm = spltAr[i].split("?")[0].split('/')[0].split(':')[0].lower();
print dm
산출
stackoverflow.com
stackoverflow.com
stackoverflow.com
stackoverflow.com
stackoverflow.com
바이올린 : https://pyfiddle.io/fiddle/23e4976e-88d2-4757-993e-532aa41b7bf0/?i=true
순수한 문자열 연산에 문제가 있습니까?
url = 'http://stackoverflow.com/questions/9626535/get-domain-name-from-url'
parts = url.split('//', 1)
print parts[0]+'//'+parts[1].split('/', 1)[0]
>>> http://stackoverflow.com
후행 슬래시를 추가하려면이 스크립트를 다음과 같이 확장하십시오.
parts = url.split('//', 1)
base = parts[0]+'//'+parts[1].split('/', 1)[0]
print base + (len(url) > len(base) and url[len(base)]=='/'and'/' or '')
아마 조금 최적화 될 수 있습니다 ...
이것은 약간 애매하지만 urlparse
양방향으로 사용합니다.
import urlparse
def uri2schemehostname(uri):
urlparse.urlunparse(urlparse.urlparse(uri)[:2] + ("",) * 4)
그 이상한 ("",) * 4
비트는 urlparse가 정확히 len(urlparse.ParseResult._fields)
= 6 의 시퀀스를 기대하기 때문입니다
I know it's an old question, but I too encountered it today. Solved this with an one-liner:
import re
result = re.sub(r'(.*://)?([^/?]+).*', '\g<1>\g<2>', url)
to get domain/hostname and Origin*
url = 'https://stackoverflow.com/questions/9626535/get-protocol-host-name-from-url'
hostname = url.split('/')[2] # stackoverflow.com
origin = '/'.join(url.split('/')[:3]) # https://stackoverflow.com
*Origin
is used in XMLHttpRequest
headers
If it contains less than 3 slashes thus you've it got and if not then we can find the occurrence between it:
import re
link = http://forum.unisoftdev.com/something
slash_count = len(re.findall("/", link))
print slash_count # output: 3
if slash_count > 2:
regex = r'\:\/\/(.*?)\/'
pattern = re.compile(regex)
path = re.findall(pattern, url)
print path
참고URL : https://stackoverflow.com/questions/9626535/get-protocol-host-name-from-url
'development' 카테고리의 다른 글
오류 : (26, 0) Gradle DSL 방법을 찾을 수 없음 : 'runProguard ()' (0) | 2020.06.24 |
---|---|
특정 조건을 기다릴 때 WebDriver로 웹 페이지 새로 고침 (0) | 2020.06.24 |
Google Analytics의 개발 작업을 조회수로 삼는 방법이 있습니까? (0) | 2020.06.24 |
인스턴스에서 클래스 이름 얻기 (0) | 2020.06.24 |
Rails after_save 콜백에서 변경된 속성을 결정 하시겠습니까? (0) | 2020.06.24 |