如果它不以http开头,我如何将http添加到网址?

Gir*_*iri 9 python url python-2.7

我的网址格式为:

google.com
www.google.com
http://google.com
http://www.google.com
Run Code Online (Sandbox Code Playgroud)

我想将所有类型的链接转换为统一格式,从 http://

http://google.com
Run Code Online (Sandbox Code Playgroud)

如何http://使用Python 预先添加URL ?

JBe*_*rdo 14

Python确实有内置函数来正确处理它,比如

p = urlparse.urlparse(my_url, 'http')
netloc = p.netloc or p.path
path = p.path if p.netloc else ''
if not netloc.startswith('www.'):
    netloc = 'www.' + netloc

p = urlparse.ParseResult('http', netloc, path, *p[3:])
print(p.geturl())
Run Code Online (Sandbox Code Playgroud)

如果要删除(或添加)www零件,则必须.netloc在调用之前编辑结果对象的字段.geturl().

因为ParseResult是一个namedtuple,你不能就地编辑它,但必须创建一个新对象.

PS:

对于Python3,它应该是 urllib.parse.urlparse


Reh*_*mat 8

我发现使用正则表达式很容易检测协议,然后在缺少时附加它:

import re
def formaturl(url):
    if not re.match('(?:http|ftp|https)://', url):
        return 'http://{}'.format(url)
    return url

url = 'test.com'
print(formaturl(url)) # http://test.com

url = 'https://test.com'
print(formaturl(url)) # https://test.com
Run Code Online (Sandbox Code Playgroud)

我希望它有帮助!


bar*_*nos 6

对于您在问题中提到的格式,您可以执行以下简单操作:

def convert(url):
    if url.startswith('http://www.'):
        return 'http://' + url[len('http://www.'):]
    if url.startswith('www.'):
        return 'http://' + url[len('www.'):]
    if not url.startswith('http://'):
        return 'http://' + url
    return url
Run Code Online (Sandbox Code Playgroud)

但请注意,您可能还没有预料到其他格式.此外,请记住,输出URL(根据您的定义)不一定是有效的(即,DNS将无法将其转换为有效的IP地址).