清除URL的http部分的最佳方法

时间:2016-11-25 21:58:44

标签: python

我正在寻找一种简单的方法来清理URL,如下所示:

  • https://已替换为http://

  • 网址缺少http(s)前缀,例如:://应附加。

有没有办法用python开箱即用?例如:

https://example.com/path/ - > http://example.com/path/

://example.com/path/ - > http://example.com/path/

谢谢!

4 个答案:

答案 0 :(得分:1)

您可以使用标准的python库re

import re

# match strings that start with either 'http://' or '://'
pattern = r'^(https://|://)' 

# replace matches with 'http://'
repl = 'http://'

test1 = 'https://stackoverflow.com'
result1 = re.sub(pattern, repl, test1, flags=re.IGNORECASE)
# result1 == 'http://stackoverflow.com'

test2 = '://stackoverflow.com'
result2 = re.sub(pattern, repl, test2, flags=re.IGNORECASE)
# result2 == 'http://stackoverflow.com'

re.sub与标记re.IGNORECASE结合使用,可以处理https://前缀的任何大小写变体,而无需将网址转换为小写,也可能会将其销毁。

答案 1 :(得分:0)

尝试以下方法:

def format_url(url): 
    if url.startswith('https'):
        url = 'http:' + url.split(':')[1]
    elif url.startswith(':'):
        url = 'http' + url
    return url

<强>输出:

>>> format_url('https://example.com/path/')
'http://example.com/path/'
>>> format_url('://example.com/path/')
'http://example.com/path/'

答案 2 :(得分:-1)

有很多方法可以做到这一点,有些涉及字符串,有些涉及组合不同的字符串,所以我会给你们两个。

使用str.replace():

url = 'https://www.python.org'
url.replace('https', 'http')
print url

将各个部分组合在一起(之前使用过这个想法,但也可以重复一遍)

if url.startswith('https://):
    url = 'http://' + rest_of_address

这可以通过检测字符串是否以https开头,然后将其替换为http(如果为true)来实现。如果你想添加另一个参数你可以使用url.endswith或者使用'if foo in url:'然后你去。

答案 3 :(得分:-3)

<?php
    if (!empty($_SERVER['HTTPS']) && ('on' == $_SERVER['HTTPS'])) {
        $uri = 'https://';
    } else {
        $uri = 'http://';
    }
    $uri .= $_SERVER['HTTP_HOST'];
    header('Location: '.$uri.'example.com/path/');
    exit;
?>

或somethnig之类的......注意它是一个php脚本....(需要php文件和php服务器)

相关问题