从URL python中删除HTTP和WWW

时间:2016-11-17 08:37:03

标签: python url

url1='www.google.com'
url2='http://www.google.com'
url3='http://google.com'
url4='www.google'
url5='http://www.google.com/images'
url6='https://www.youtube.com/watch?v=6RB89BOxaYY

如何在Python中从url中删除http(s)www

3 个答案:

答案 0 :(得分:7)

您可以使用regex

url = 'http://www.google.com/images'
url = url.replace("http://www.","")
print url

或者您可以使用regular expressions

import re
url = re.compile(r"https?://(www\.)?")
url.sub('', 'http://www.google.com/images').strip().strip('/')

答案 1 :(得分:2)

可以使用正则表达式,具体取决于数据的严格程度。 http和www总是会在那里吗?你有没有想过https或w3网站?

import re
new_url = re.sub('.*w\.', '', url, 1)

1不会损害以w结尾的网站。

澄清后编辑

我会做两个步骤:

if url.startswith('http'):
    url = re.sub(r'https?:\\', '', url)
if url.startswith('www.'):
    url = re.sub(r'www.', '', url)

答案 2 :(得分:1)

更优雅的解决方案是使用urlparse:

from urllib.parse import urlparse

def get_hostname(url, uri_type='both'):
    """Get the host name from the url"""
    parsed_uri = urlparse(url)
    if uri_type == 'both':
        return '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)
    elif uri_type == 'netloc_only':
        return '{uri.netloc}'.format(uri=parsed_uri)

根据链接,第一个选项包括httpshttp,第二个部分netloc包括您要查找的内容。