【问题标题】:Add parameters to a given URL in Python在 Python 中将参数添加到给定的 URL
【发布时间】:2020-09-05 10:10:13
【问题描述】:

我要添加以下参数:

params= {'Context' : { "Country":"US", "Region":"US", "Language":"en", "Segment":"dhs", "CustomerSet":"19"}, 'itemIdentifiers' : ['210-amsr','320-9704']}

到基本 URL = https://www.catalogue.com/getdetail?

最终的 URL 看起来像这样:https://www.catalogue.com/getdetail?Context={"Country":"US","Region":"US","Language":"en","Segment":"dhs","CustomerSet":"19"}&itemIdentifiers=210-amsr,320-9704

我尝试了以下方法: api_url = url+parse.urlencode(params, doseq=True)

但我最终得到:https://www.catalogue.com/getdetail?Context=Country&Context=Region&Context=Language&Context=Segment&Context=CustomerSet&itemIdentifiers=210-amsr&itemIdentifiers=320-9704

【问题讨论】:

  • 你自己试过了吗?使用 requests 库怎么样?
  • 我尝试了以下方法:api_url = url+parse.urlencode(params, doseq=True) 但最终得到:https://www.catalogue.com/getdetail?Context=Country&Context=Region&Context=Language&Context=Segment&Context=CustomerSet&itemIdentifiers=210-amsr&itemIdentifiers=320-9704 我也尝试了请求库,但得到了类似的结果。
  • 您对使用requests 有什么感觉 - 它让这一切变得更加愉快。这样您就不需要将其添加到您的 URL,而只需将您的 params dict 作为 params arg 传递给您的请求函数。
  • 我试过了,它成功了,谢谢:)

标签: python urllib urllib3


【解决方案1】:

requests 可以为您处理这个问题:

import requests

base_url = r"https://www.catalogue.com/getdetail"
params= {
    "Context" : { 
        "Country": "US", 
        "Region" : "US", 
        "Language" : "en", 
        "Segment" : "dhs", 
        "CustomerSet" : "19"
     }, 
     "itemIdentifiers" : ['210-amsr', '320-9704'],
}

requests.get(base_url, params=params)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 2015-04-24
    • 2015-06-20
    相关资源
    最近更新 更多