为了账号安全,请及时绑定邮箱和手机立即绑定

JSONDecoder 错误 - 使用 Python 访问 Google Translate

JSONDecoder 错误 - 使用 Python 访问 Google Translate

三国纷争 2023-03-08 10:47:05
我正在学习在 Python 中使用 HTTP 请求,使用由 TopCoder 培训挑战提供的这个 HTTP 请求(仅用于学习目的!没有任何形式的补偿),您必须在其中访问 Google Translate API:curl --location --request POST 'https://translate.google.com/translate_a/single?client=at&dt=t&dt=ld&dt=qca&dt=rm&dt=bd&dj=1&hl=%25s&ie=UTF-8&oe=UTF-8&inputm=2&otf=2&iid=1dd3b944-fa62-4b55-b330-74909a99969e&' \--header 'Content-Type: application/x-www-form-urlencoded' \--header 'User-Agent: AndroidTranslate/5.3.0.RC02.130475354-53000263 5.1 phone TRANSLATE_OPM5_TEST_1' \--data-urlencode 'sl=de' \--data-urlencode 'tl=en' \--data-urlencode 'q=Hallo' 我想知道如何在我的 Python 应用程序中发出等效请求?任何帮助表示赞赏。到目前为止我有:安装并导入requests明白我需要将我的 POST 请求存储在一个变量中并用 JSON 解析它。问题是我收到 JSONDecoder 错误Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "C:\Users\myname\Documents\Code\GoogleTranslateApiPy\env\lib\site-packages\requests\models.py", line 898, in json    return complexjson.loads(self.text, **kwargs)  File "c:\users\myname\appdata\local\programs\python\python38-32\lib\json\__init__.py", line 357, in loads    return _default_decoder.decode(s)  File "c:\users\myname\appdata\local\programs\python\python38-32\lib\json\decoder.py", line 337, in decode    obj, end = self.raw_decode(s, idx=_w(s, 0).end())  File "c:\users\myname\appdata\local\programs\python\python38-32\lib\json\decoder.py", line 355, in raw_decode    raise JSONDecodeError("Expecting value", s, err.value) from Nonejson.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)使用此 Python 请求(我尝试尽可能地翻译 curl 请求):import requestsheaders = {    'Content-Type': 'application/x-www-form-urlencoded',    'User-Agent': 'AndroidTranslate/5.3.0.RC02.130475354-53000263 5.1 phone TRANSLATE_OPM5_TEST_1',}我觉得这里缺少一些基本的东西。Google 当前文档中对翻译的请求与此提供的请求不同,但我想知道我如何才能以这种方式工作,以防将来我收到这样的 curl 命令。
查看完整描述

1 回答

?
郎朗坤

TA贡献1921条经验 获得超9个赞

两件事情:

  1. 您必须执行POST 请求(当前您正在执行 get 请求)

  1. 您不包括请求的正文。例如,curl 调用包括这样的 url 编码数据:data-urlencode 'q=Hallo'。您也必须在您的发布请求中包含此参数,提供的链接向您展示了如何操作。这是将放入字典中的键值,例如 {q: 'Hallo', ...}

PS:我 90% 确定你也应该将你当前在元组中的查询参数转换为字典。因此,您将发布带有标题、参数和数据的帖子。


查看完整回答
反对 回复 2023-03-08
  • 1 回答
  • 0 关注
  • 60 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信