【问题标题】:Using Python request.get param but it gives me wrong url使用 Python request.get 参数,但它给了我错误的 url
【发布时间】:2019-03-05 20:02:35
【问题描述】:

我正在尝试使用 Python 请求库从 Steam 中抓取一些数据。但首先我需要修改我的网址

例如,如果我想访问带有标签的游戏​​

  • 2D [id : 3871]
  • 1980 年代 [id : 7743]

https://store.steampowered.com/search?tags=7743%2C3871

这是我需要的链接。但是当我这样做时

steam_url = "https://store.steampowered.com/search?"
search = request.get(steam_url, params = {'tags' : [7743, 3871]})

我得到了这个网址

https://store.steampowered.com/search?tags=7743&tags=3871

只显示 2D 游戏 [id : 3871]

为了解决这个问题,我尝试这样做

steam_url = "https://store.steampowered.com/search?"
search = get(steam_url, params = {'tags' : '%2C'.join(list(map(str,[7743, 3871])))})

然后我得到这个网址

https://store.steampowered.com/search?tags=7743%252C3871

我不明白为什么这些 id 之间有 %252C

我该怎么办?

【问题讨论】:

标签: python python-requests


【解决方案1】:

试试下面的代码。我对代码的测试给出了https://store.steampowered.com/search?tags=7743%2C3871

import requests

steam_url = "https://store.steampowered.com/search?"
search = requests.get(steam_url, params = {'tags' : '7743,3871'})

print(search.url)

【讨论】:

    【解决方案2】:

    %2C, 的编码hexadecimal value 的URL。当您手动输入 %2C 时,request 包将尝试将实际值 %2C 安全地进行 URL 编码,这将导致 %252C(更具体地说,它将尝试将 % 转换为 @987654330 @)。

    您正在尝试对值进行 url 编码,但 request 包也是如此,这意味着它是双重编码的。

    如果您只是在函数中手动编写,,它应该可以工作。

    steam_url = "https://store.steampowered.com/search?"
    search = get(steam_url, params = {'tags' : ','.join(list(map(str,[7743, 3871])))})
    

    不过,正如Hassan Voyeau所说,你不需要把函数弄得那么复杂,你可以通过{'tags': '7743,3871'}正常写值,只要你不尝试对任何值进行URL编码手动。

    【讨论】:

    • 没错。我想知道为什么我的代码被否决了。我实际测试过它并且知道它有效。
    • 如果我在没有任何解释正确回答问题以及如何解决问题的情况下被否决,我宁愿直接删除我的答案,而不是提供帮助。
    • 感谢你们两位,这些 cmets 真的启发了我。这个问题对我来说是一个巨大的挫折,非常感谢!
    • 如果没有解释性评论,并且您确信您的答案是好的,那么不要介意反对票。有些人可能只是因为他们可以投票而投票,没有特别的理由。 +1 让我让你振作起来:)
    • 谢谢@t.m.adam,我太幼稚了,已经心情不好了。感谢您的积极性和 +1 :)
    【解决方案3】:

    我不明白为什么这些 id 之间有 %252C。

    因为您使用的是'%2C'.join,它被转义为%252C%25 是百分号。使用','.join 并让requests.get 进行转义。

    【讨论】:

      猜你喜欢
      • 2020-02-09
      • 1970-01-01
      • 2021-12-30
      • 2021-06-03
      • 2019-08-30
      • 2018-09-27
      • 2020-09-15
      • 2022-10-01
      • 1970-01-01
      相关资源
      最近更新 更多