使用源URL创建具有不同路径和方案的新URL的Pythonic方法是什么?
假设我有一个网址,它可能是HTTPS,也可能不是,而且这个网址的主机名我无法控制,但它的格式大概是这样的:
http://example.com/special/content 或者 https://example.com/special/content
我想用Python来把这个网址的协议改成HTTPS,并把路径改成/something/else,最简单的做法是什么呢?
我现在的做法是:
from urlparse import urlsplit, urljoin, urlunsplit
currenturl = "http://example.com/some/content"
parts = list(urlsplit(urljoin(currenturl, "/something/else")))
parts[0]="https"
newurl = urlunsplit(parts)
有没有什么建议呢?
建议(来自@ignacio-vazquez-abrams)
from urlparse import urlparse, urljoin, urlunparse
currenturl = "http://example.com/some/content"
parts = list(urlparse(currenturl))
parts[0]="https"
parts[2]="/something/else" # If only path needed changing (or see bellow...)
newurl = urlunparse(parts)
newurl = urljoin(newurl, "/something/else") # If we need to rewrite everything
# after network loc
1 个回答
4
你已经很接近了。可以用 urlparse.urlparse()
这个工具把网址拆分开,取出你需要的部分,然后再用 urlparse.urlunparse()
把它们组合起来。