import requests import time headers = { 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36', 'referer': 'http://fund.eastmoney.com/400015.html?spm=search' } params = { "callback": "jQuery18303118265739643302_1690164521076", "fundCode": "400015", "pageIndex": "6", "pageSize": "20", "startDate": "", "endDate": "", "_": "1690165052233" } url = 'http://api.fund.eastmoney.com/f10/lsjz' res = requests.get(url, params=params, headers=headers) LSJZ = res.json()['Data']['LSJZList'] for i in LSJZ: print("单位净值:", i['DWJZ']) 给出的代码还是运行不了,并有以下错误提示: File "C:\Users\刘岩\.spyder-py3\temp.py", line 22, in <module> LSJZ = res.json()['Data']['LSJZList'] File "F:\anaconda\anaconda\lib\site-packages\requests\models.py", line 975, in json raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) JSONDecodeError: Expecting value
时间: 2023-09-28 08:06:23 浏览: 123
这个错误提示表明在尝试解析响应的JSON数据时出现了问题。错误的原因可能是,返回的响应内容不是有效的JSON格式。
为了解决这个问题,你可以添加一些错误处理代码来检查响应是否成功,并确保返回的数据是有效的JSON格式。以下是修改后的代码:
```python
import requests
import time
headers = {
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36',
'referer': 'http://fund.eastmoney.com/400015.html?spm=search'
}
params = {
"callback": "jQuery18303118265739643302_1690164521076",
"fundCode": "400015",
"pageIndex": "6",
"pageSize": "20",
"startDate": "",
"endDate": "",
"_": "1690165052233"
}
url = 'http://api.fund.eastmoney.com/f10/lsjz'
res = requests.get(url, params=params, headers=headers)
try:
data = res.json()
LSJZ = data['Data']['LSJZList']
for i in LSJZ:
print("单位净值:", i['DWJZ'])
except ValueError:
print("无效的JSON数据")
```
这个修改后的代码在解析JSON数据之前添加了一个 `try-except` 块。在 `try` 块中,我们尝试解析JSON数据并提取所需的信息。如果解析过程中出现错误,会抛出 `ValueError` 异常。在 `except` 块中,我们捕获这个异常并打印出错误信息。
通过这个修改,代码将能够处理无效的JSON数据,避免触发 `JSONDecodeError` 异常。
阅读全文