How can I prepend http to a url if it doesn't begin with http?

前端 未结 4 1605
陌清茗
陌清茗 2021-01-08 00:21

I have urls formatted as:

google.com
www.google.com
http://google.com
http://www.google.com

I would like to convert all type of links to a

4条回答
  •  不思量自难忘°
    2021-01-08 00:27

    I found it easy to detect the protocol with regex and then append it if missing:

    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
    

    I hope it helps!

提交回复
热议问题