pycharm写爬虫百度翻译然后报错json.decoder.JSONDecodeError:

import requests

userinput = input("请输入想要翻译的单词: ")
data = {"from":"en","to":"zh","query":"userinput","transtype":"realtime","simple_means_flag":"3"}
r = requests.post("http://fanyi.baidu.com/v2transapi/q", json=data)

print(r.json()["trans_result"]["data"][0]["dst"])

报错信息如下:
/Users/renxiaobo/PycharmProjects/untitled/venv/bin/python /Users/renxiaobo/PycharmProjects/untitled/test/test01.py
请输入想要翻译的单词: fuck
Traceback (most recent call last):
File "/Users/renxiaobo/PycharmProjects/untitled/test/test01.py", line 7, in
print(r.json()["trans_result"]["data"][0]["dst"])
File "/Users/renxiaobo/PycharmProjects/untitled/venv/lib/python3.6/site-packages/requests/models.py", line 892, in json
return complexjson.loads(self.text, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Process finished with exit code 1

2个回答

先看看r.json返回的是什么数据。

有两个问题
1.百度翻译的URL有变化,没有后面的q
2. userinput 不要加引号

下面是可能使用的代码

 #!/usr/bin/env python                                                                                            
 # coding=utf-8   

import requests
userinput = input("请输入想要翻译的单词: ")
data = {"from":"en","to":"zh","query":userinput,"transtype":"realtime","simple_means_flag":"3"}

r = requests.post("http://fanyi.baidu.com/v2transapi", data)
print(r.json()["trans_result"]["data"][0]["dst"])
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问