我是 python 的新手,所以请多多包涵 :)
我想知道 python 中是否有任何内置方法可以将变量附加到 URL 而不管它的结构。
我想将一个 URL 变量 (test=1) 添加到一个可以具有以下任何结构的 URL
http://www.aaa.com (would simply add "/?test=1") to the end
http://www.aaa.com/home (like the one above, would simply add "/?test=1") to the end
http://www.aaa.com/?location=home (would figure out there's already a ? being used, and would add &test=1 to the end)
http://www.aaa.com/?location=home&page=1 (like the one above, would figure out there's already a ? being used, and would add &test=1 to the end)
我很乐意自己编写一些东西来做这件事,但是如果 python 已经可以以某种方式做到这一点,我会非常乐意使用任何可以节省我一些时间的内置功能;-)
提前致谢
最佳答案
同时使用 Lennart Regebro的和Adam Vendenberg的建议,你可以这样做:
import urllib
import urlparse
query=urllib.urlencode({"test":1})
urls=['http://www.aaa.com',
'http://www.aaa.com/home',
'http://www.aaa.com/?location=home',
'http://www.aaa.com/?location=home&page=1']
for url in urls:
x=urlparse.urlparse(url)
new_query=(x.query+'&'+query) if x.query else query
y=urlparse.urlunparse((x.scheme,x.netloc,x.path,x.params,new_query,x.fragment))
print(y)
产量
http://www.aaa.com?test=1
http://www.aaa.com/home?test=1
http://www.aaa.com/?location=home&test=1
http://www.aaa.com/?location=home&page=1&test=1
关于python - 自动创建有效链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4587627/