如果 URL 不以 http 开头,我如何将 http 添加到 url 之前? [英] How can I prepend http to a url if it doesn't begin with http?
问题描述
我的网址格式如下:
google.com
www.google.com
http://google.com
http://www.google.com
我想将所有类型的链接转换为统一格式,以 http://
I would like to convert all type of links to a uniform format, starting with http://
http://google.com
如何使用 Python 在 URL 前加上 http://
?
How can I prepend URLs with http://
using Python?
推荐答案
Python 确实有内置函数可以正确处理,例如
Python do have builtin functions to treat that correctly, like
p = urlparse.urlparse(my_url, 'http')
netloc = p.netloc or p.path
path = p.path if p.netloc else ''
if not netloc.startswith('www.'):
netloc = 'www.' + netloc
p = urlparse.ParseResult('http', netloc, path, *p[3:])
print(p.geturl())
如果要删除(或添加)www
部分,则必须在调用 .geturl() 之前编辑结果对象的
..netloc
字段)
If you want to remove (or add) the www
part, you have to edit the .netloc
field of the resulting object before calling .geturl()
.
因为 ParseResult
是一个命名元组,你不能就地编辑它,而必须创建一个新对象.
Because ParseResult
is a namedtuple, you cannot edit it in-place, but have to create a new object.
附注:
对于Python3,应该是urllib.parse.urlparse
For Python3, it should be urllib.parse.urlparse
这篇关于如果 URL 不以 http 开头,我如何将 http 添加到 url 之前?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!