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

前端 未结 4 1626
陌清茗
陌清茗 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:36

    def fix_url(orig_link):
        # force scheme 
        split_comps = urlsplit(orig_link, scheme='https')
        # fix netloc (can happen when there is no scheme)
        if not len(split_comps.netloc):
            if len(split_comps.path):
                # override components with fixed netloc and path
                split_comps = SplitResult(scheme='https',netloc=split_comps.path,path='',query=split_comps.query,fragment=split_comps.fragment)
            else: # no netloc, no path 
                raise ValueError
        return urlunsplit(split_comps)
    

提交回复
热议问题