使用Python request.get参数,但它给我错误的URL

时间:2018-09-30 14:25:04

标签: python python-requests

我正在尝试使用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])))})

然后我得到这个URL

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

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

我该怎么办?

3 个答案:

答案 0 :(得分:2)

  

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

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

答案 1 :(得分: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 :(得分:0)

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

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

如果您只是在函数中手动编写,,那么它将起作用。

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

但是,就像Hassan Voyeau所说的那样,您不需要使函数变得如此复杂,只要您不尝试使用URL,就可以用{'tags': '7743,3871'}正常地写值。 -手动编码任何值。