我正在使用一个返回urls的应用程序,用Flask
编写。我希望向用户显示的URL
尽可能干净,因此我想从中删除http://
。我查看并找到了urlparse
库,但找不到任何如何执行此操作的示例。
最好的解决方法是什么,如果urlparse
过度杀戮有更简单的方法吗?只是使用常规字符串解析工具从URL中删除“http://
”子字符串是不好的做法还是会导致问题?
答案 0 :(得分:7)
我认为urlparse
没有提供单一的方法或功能。我就是这样做的:
from urlparse import urlparse
url = 'HtTp://stackoverflow.com/questions/tagged/python?page=2'
def strip_scheme(url):
parsed = urlparse(url)
scheme = "%s://" % parsed.scheme
return parsed.geturl().replace(scheme, '', 1)
print strip_scheme(url)
输出:
stackoverflow.com/questions/tagged/python?page=2
如果您使用(仅)简单的字符串解析,您必须自己处理http[s]
,以及可能的其他方案。此外,这处理该方案的奇怪外壳。
答案 1 :(得分:1)
如果您以编程方式使用这些而不是使用替换,我建议让urlparse重新创建没有方案的URL。
ParseResult对象是一个元组。因此,您可以创建另一个删除不需要的字段。
# py2/3 compatibility
try:
from urllib.parse import urlparse, ParseResult
except ImportError:
from urlparse import urlparse, ParseResult
def strip_scheme(url):
parsed_result = urlparse(url)
return ParseResult('', *parsed_result[1:]).geturl()
您可以通过简单地用空字符串替换输入来删除parsedresult的任何组件。
重要的是要注意这个答案与@Lukas Graf的答案之间存在功能差异。最可能的功能差异是url的'//'组件在技术上不是方案,所以这个答案将保留它,而它将保留在这里。
>>> Lukas_strip_scheme('https://yoman/hi?whatup')
'yoman/hi?whatup'
>>> strip_scheme('https://yoman/hi?whatup')
'//yoman/hi?whatup'
答案 2 :(得分:1)
一个简单的正则表达式搜索和替换工作。
import re
def strip_scheme(url: str):
return re.sub(r'^https?:\/\/', '', url)
答案 3 :(得分:0)
我已经在Flask库和扩展中看到了这一点。值得注意的是,您可以尽管做到这一点,但它确实使用了ParseResult / SplitResult的受保护成员(._replace)。
url = 'HtTp://stackoverflow.com/questions/tagged/python?page=2'
split_url = urlsplit(url)
# >>> SplitResult(scheme='http', netloc='stackoverflow.com', path='/questions/tagged/python', query='page=2', fragment='')
split_url_without_scheme = split_url._replace(scheme="")
# >>> SplitResult(scheme='', netloc='stackoverflow.com', path='/questions/tagged/python', query='page=2', fragment='')
new_url = urlunsplit(split_url_without_scheme)