Python爬取Quantalys网站数据时遇JSONDecodeError求助
问题分析与解决方案
错误原因
JSONDecodeError 说明你请求返回的内容不是有效的JSON格式,大概率是网站的反爬机制拦截了你的POST请求,返回了HTML验证页面(比如人机验证、登录提示)或者错误页面,而非预期的JSON数据。
排查与解决步骤
- 先确认返回内容:在调用
response.json()前,先打印response.text查看实际返回的内容,判断是否被拦截:response = requests.post('https://www.quantalys.com/SocieteGestion/ListeData', headers=headers, data=data) print(response.text) # 查看返回的实际内容 - 补充必要请求头:网站通常会校验
Referer(请求来源)和会话Cookie,需要先访问列表页获取有效Cookie,再携带完整请求头发起POST。 - 模拟完整请求流程:先GET访问目标列表页,获取会话Cookie,再用该Cookie发起POST请求,同时添加
Referer头。
修改后的示例代码
import requests import pandas as pd headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36', 'Referer': 'https://www.quantalys.com/SocieteGestion/Liste' } # 先GET列表页,获取会话Cookie session = requests.Session() session.get('https://www.quantalys.com/SocieteGestion/Liste', headers=headers) data = { 'columns[0][name]': 'ID_Societe', 'columns[1][name]': 'sNom', 'columns[2][name]': 'sURL', 'columns[3][name]': 'sGroupe', 'columns[4][name]': 'nFonds', 'columns[5][name]': 'nParts', 'columns[6][name]': 'nEncours', 'columns[7][name]': 'dtEncours', 'columns[8][name]': 'sAwards', 'columns[9][name]': 'nAAA', 'columns[10][name]': 'nAA', 'columns[11][name]': 'nA', 'columns[12][name]': 'dtAwards', 'order[0][column]': '2', 'order[0][dir]': 'asc', 'start': '0', 'length': '10', } # 用会话发起POST请求 response = session.post('https://www.quantalys.com/SocieteGestion/ListeData', headers=headers, data=data) # 先确认返回是否为JSON try: df_list_sdg = pd.DataFrame(response.json()['data']) print(df_list_sdg) except Exception as e: print(f"解析失败,返回内容:{response.text}") print(f"错误信息:{str(e)}")
额外注意事项
- 如果还是被拦截,可能需要处理人机验证,这时候单纯用requests很难绕过,可能需要结合
selenium或者playwright模拟真实浏览器行为。 - 确保请求的
data参数和浏览器实际发送的一致,可以通过浏览器开发者工具的Network面板查看POST请求的Form Data,对比你的参数是否完整。
内容的提问来源于stack exchange,提问作者jacques
相关产品推荐
相关产品推荐

