gpt4 book ai didi

python - 在请求 python 中读取特殊字符的问题。各种不成功的尝试

转载 作者:行者123 更新时间:2023-12-04 03:47:45 31 4
gpt4 key购买 nike

我试图在堆栈上找到类似的问题,但我还没有找到解决我的问题的方法。
我在python中有以下代码

        headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
'Accept': '*/*',
'Accept-Language': 'pt-BR,pt;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
'Accept-Encoding': 'gzip, deflate, br',
'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest',
'Connection': 'keep-alive',
}


response = requests.request("POST", URL_ENDPOINT, headers=headers, data=payload_novo)
print(response.text)
输出是:
{"output": "\n                        <h3 class=\"titulo-servico\">Local de vota\u00e7\u00e3o</h3>\n                        <p></p>\n                        <p>Os dados informados (nome, data de nascimento ou filia\u00e7\u00e3o) n\u00e3o conferem com aqueles constantes do Cadastro Eleitoral.</p>\n                        <p></p>\n                        <button type=\"button\" \n                            class=\"btn btn-amarelo\" \n
onclick=\"exibirConsultaLocalVotacao()\">\n Nova consulta\n </button>\n </p>\n ", "type": "success"}
看到他带着 "\\ u00e7 \ u00e3o" 之类的字符回来了.我尝试了各种方式通过解码来解码,但结果总是一样的
但是,如果我创建一个新的python文件并将此返回值放在一个变量中并打印出来,结果将毫无问题地显示出来,即特殊字符起作用
myString= '''{"output": "\n                        <h3 class=\"titulo-servico\">Local de vota\u00e7\u00e3o</h3>\n                        <p></p>\n                        <p>Os dados informados (nome, data de nascimento ou filia\u00e7\u00e3o) n\u00e3o conferem com aqueles constantes do Cadastro Eleitoral.</p>\n                        <p></p>\n                        <button type=\"button\" \n                            class=\"btn btn-amarelo\" \n
onclick=\"exibirConsultaLocalVotacao()\">\n Nova consulta\n </button>\n </p>\n ", "type": "success"}'''


print(myString)
正确的输出是:
{"output": "
<h3 class="titulo-servico">Local de votação</h3>
<p></p>
<p>Os dados informados (nome, data de nascimento ou filiação) não conferem com aqueles constantes do Cadastro Eleitoral.</p>
<p></p>
<button type="button"
class="btn btn-amarelo"

onclick="exibirConsultaLocalVotacao()">
Nova consulta
</button>
</p>
", "type": "success"}
注意:
退出 1 段: <h3 class=\"titulo-servico\">Local de vota\u00e7\u00e3o</h3>退出2段: <h3 class="titulo-servico">Local de votação</h3>

最佳答案

这可能是以下两个问题之一:

  • 您正在打印的响应实际上是一个 JSON 负载。在这种情况下,正确的解码方式不是通过 text但是 json() :
    print(response.json())
    或更具体地说
    print(response.json()["output"])
  • 可能出错的第二件事是请求的自动字符集编码检测。
    您可以通过打印 encoding 来验证它是否正确检测到 utf-8响应字段:
    print(response.encoding)
    如果出现意外,您可以在使用 text 之前显式设置它或 json领域:
    response.encoding = 'utf-8'
  • 关于python - 在请求 python 中读取特殊字符的问题。各种不成功的尝试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64886208/

    31 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com