【问题标题】:Python URLencoding Specific ResultsPython URLencoding 特定结果
【发布时间】:2020-04-01 18:53:38
【问题描述】:

我正在从 Python 3.8.2 中的数据库查询

我需要 urlencoded 结果是:

data = {"where":{"date":"03/30/20"}}
needed_results = ?where=%7B%22date%22%3A%20%2203%2F30%2F20%22%7D

我尝试了以下方法

import urllib.parse

data = {"where":{"date":"03/30/20"}}

print(urllib.parse.quote_plus(data))

当我这样做时,我会得到以下内容

Traceback (most recent call last):
  File "C:\Users\Johnathan\Desktop\Python Snippets\test_func.py", line 17, in <module>
    print(urllib.parse.quote_plus(data))
  File "C:\Users\Johnathan\AppData\Local\Programs\Python\Python38-32\lib\urllib\parse.py", line 855, in quote_plus
    string = quote(string, safe + space, encoding, errors)
  File "C:\Users\Johnathan\AppData\Local\Programs\Python\Python38-32\lib\urllib\parse.py", line 839, in quote
    return quote_from_bytes(string, safe)
  File "C:\Users\Johnathan\AppData\Local\Programs\Python\Python38-32\lib\urllib\parse.py", line 864, in quote_from_bytes
    raise TypeError("quote_from_bytes() expected bytes")
TypeError: quote_from_bytes() expected bytes

我尝试了其他几种方法并收到:?where=%7B%27date%27%3A+%2703%2F30%2F20%27%7D

长话短说,我需要对以下内容进行 url 编码


data = {"where":{"date":"03/30/20"}}

needed_encoded_data = ?where=%7B%22date%22%3A%20%2203%2F30%2F20%22%7D

谢谢

【问题讨论】:

    标签: python python-3.x curl python-requests urlencode


    【解决方案1】:

    where 是一个字典 - 不能进行 url 编码。您需要先将其转换为字符串或字节对象。

    你可以通过json.dumps做到这一点

    import json
    import urllib.parse
    
    data = {"where":{"date":"03/30/20"}}
    
    print(urllib.parse.quote_plus(json.dumps(data)))
    

    输出:

    %7B%22where%22%3A+%7B%22date%22%3A+%2203%2F30%2F20%22%7D%7D
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-21
      • 2019-09-19
      • 1970-01-01
      相关资源
      最近更新 更多