python - 自动创建有效链接

标签 python url

我是 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/

相关文章:

python - Pandas 从具有名称列表的列中获取最常见的名称

python - 如何在numpy中计算超过num_classes - 1 LDA方向?

html - 如何强制 jasper 报告中的图像 url 导出为 HTML?

java - 使用 Java 访问 URL

google-maps - google maps api,提供的API key 无效

java - 与 python psycopg2 相比,使用 clojure jdbc 将文件记录插入 postgres db 需要很长时间

Python Flask - request.json 返回 None 类型而不是 json 字典

python - 如何直接运行Python包的主脚本?

string - 在 url 参数中获取字节数组作为字符串

c# - 从 URL 获取主机域?