Python 清除URL的http部分的最佳方法
我正在寻找一种清理URL的简单方法,如下所示:Python 清除URL的http部分的最佳方法,python,Python,我正在寻找一种清理URL的简单方法,如下所示: https://替换为http:// 缺少http(s)前缀的URL,例如:://应该附加前缀 有没有一种方法可以用python实现这一点?例如: https://example.com/path/->http://example.com/path/ ://example.com/path/->http://example.com/path/ 谢谢 <?php if (!empty($_SERVER['HTTPS']) &
替换为https://
http://
- 缺少http(s)前缀的URL,例如:
应该附加前缀://
https://example.com/path/
->http://example.com/path/
://example.com/path/
->http://example.com/path/
谢谢
<?php
if (!empty($_SERVER['HTTPS']) && ('on' == $_SERVER['HTTPS'])) {
$uri = 'https://';
} else {
$uri = 'http://';
}
$uri .= $_SERVER['HTTP_HOST'];
header('Location: '.$uri.'example.com/path/');
exit;
?>
或者类似的东西…请注意,这是一个php脚本…(.php文件和php服务器是必需的)尝试以下操作:
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/'
有很多方法可以做到这一点,一些涉及到字符串,另一些涉及到组合不同的字符串,所以我给你们两种方法 使用str.replace(): 将各个部分组合在一起(这个想法以前使用过,但不妨重复一下)
其工作原理是检测字符串是否以https开头,如果为true,则将其替换为http。如果您想添加另一个参数,您可以使用url.endswith或使用“If foo in url:”然后就可以了。您可以使用标准python库来实现这一点
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.IGNORECASE
一起使用将允许您处理https://
前缀的任何大小写变化,而不必将URL转换为小写,甚至可能会破坏它。您是否尝试过使用正则表达式?这是一个问题。仅此行就足以满足这两种情况<代码>url='http:'+url.split(':')[1]
if url.startswith('https://):
url = 'http://' + rest_of_address
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'