取消引用后如何避免 url 中的方括号

how to avoid square brackets from url after unquote

我决定像这样在 URL 上添加一个查询字符串

import urllib
import urllib.parse
from urllib.parse import urlencode

url = "https://datausa.io/api/data?Geography=04000US06&drilldowns=Race,Ethnicity&measures=Hispanic%20Population,Hispanic%20Population%20Moe"
parts = urllib.parse.urlparse(url)
query_dict = urllib.parse.parse_qs(parts.query)  
query_dict['Geography'] = '04000US24'
new_parts = list(parts)
new_parts[4] = urlencode(query_dict)
print(urllib.parse.urlunparse(new_parts))

我得到了这个结果

https://datausa.io/api/data?Geography=04000US24&drilldowns=%5B%27Race%2CEthnicity%27%5D&measures=%5B%27Hispanic+Population%2CHispanic+Population+Moe%27%5D

所以这个 url 不再起作用了。所以我使用了取消引号,像这样

from urllib.parse import unquote
url = unquote('https://datausa.io/api/data?Geography=04000US24&drilldowns=%5B%27Race%2CEthnicity%27%5D&measures=%5B%27Hispanic+Population%2CHispanic+Population+Moe%27%5D')
print(url)

但是得到了这个

https://datausa.io/api/data?Geography=04000US24&drilldowns=['Race,Ethnicity']&measures=['Hispanic+Population,Hispanic+Population+Moe']

这个url也不行。

我怎样才能去掉方括号并回到原来的状态url https://datausa.io/api/data?Geography=04000US24&drilldowns=Race,Ethnicity&measures=Hispanic%20Population,Hispanic%20Population%20Moe ?

谢谢

使用doseq参数。

new_parts[4] = urlencode(query_dict, doseq=True)

有关参数

的更多信息,请参阅 urllib.parse.urlencode 上的文档