浏览器能正常访问URL获取JSON,但是pycharm里调不通

首次调通:可运行代码块:(能拿到结果但是有些小的报错)
import requests
import time
import json
from urllib3.exceptions import InsecureRequestWarning# 禁用SSL证书验证警告(可选,仅测试用)
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)# 目标URL(确保原始URL不带t参数)
url = "https://airtw.moenv.gov.tw/json/AQI/Taiwan_2025110607.json"
timestamp = int(time.time() * 1000)
url_with_ts = f"{url}?t={timestamp}" # 正确添加时间戳参数# 代理配置(替换为你的实际代理)
proxies = {"http": "http://127.0.0.1:7890","https": "http://127.0.0.1:7890"
}# 完整请求头
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36","Accept": "application/json, text/javascript, */*; q=0.01","Referer": "https://airtw.moenv.gov.tw/","X-Requested-With": "XMLHttpRequest"
}try:print("访问URL:", url_with_ts)response = requests.get(url_with_ts,headers=headers,proxies=proxies,timeout=20,verify=False # 临时关闭SSL验证(生产环境不建议))print(f"状态码: {response.status_code}")print(f"响应内容类型: {response.headers.get('Content-Type', '未知')}")print(f"原始响应(前500字符): {response.text[:500]}")# 解析JSON(返回的是列表,直接赋值给data)data = response.json()# 直接用len(data)获取列表长度(因为data是列表)print("✓ 连接成功!JSON解析成功,数据条数:", len(data))except json.JSONDecodeError as e:print(f"\n✗ JSON解析失败: {e}")
except requests.exceptions.ProxyError:print("\n✗ 代理错误:请检查代理地址和端口")
except ConnectionResetError: # 捕获内置的连接重置异常print("\n✗ 连接被服务器强制关闭:建议更换代理节点")
except requests.exceptions.ConnectionError: # 捕获其他连接错误print("\n✗ 网络连接错误:请检查是否正常")
except Exception as e:print(f"\n✗ 其他错误: {str(e)}")
报错信息:
E:\project\hunan_couse_about\OpenData-master\OpenData-master\.venv\Scripts\python.exe E:\project\hunan_couse_about\OpenData-master\OpenData-master\test6.py 访问URL: https://airtw.moenv.gov.tw/json/AQI/Taiwan_2025110607.json?t=1762396363336?t=1762412374692 E:\project\hunan_couse_about\OpenData-master\OpenData-master\.venv\Lib\site-packages\urllib3\connectionpool.py:1097: InsecureRequestWarning: Unverified HTTPS request is being made to host '127.0.0.1'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings warnings.warn( Traceback (most recent call last): File "E:\project\hunan_couse_about\OpenData-master\OpenData-master\test6.py", line 44, in <module> print("✓ 连接成功!JSON解析成功,数据条数:", len(data.get("sites", []))) ^^^^^^^^ AttributeError: 'list' object has no attribute 'get' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "E:\project\hunan_couse_about\OpenData-master\OpenData-master\test6.py", line 51, in <module> except requests.exceptions.ConnectionResetError: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: module 'requests.exceptions' has no attribute 'ConnectionResetError'. Did you mean: 'ConnectionError'? 状态码: 200 响应内容类型: application/json 原始响应(前500字符): [
一、核心错误 1:'list' object has no attribute 'get'
原因:
服务器返回的 JSON 顶层结构是列表(list),但代码中错误地用了字典(dict)的get方法(data.get("sites", []))。列表没有get方法,因此报错。
解决:
将len(data.get("sites", []))改为直接获取列表长度len(data)
二、核心错误 2:module 'requests.exceptions' has no attribute 'ConnectionResetError'
原因:
ConnectionResetError是Python 内置的异常(属于OSError的子类),而非requests.exceptions模块中的异常。代码错误地将其写为requests.exceptions.ConnectionResetError,导致找不到该异常类。
解决:
直接捕获内置的ConnectionResetError,或捕获更通用的requests.exceptions.ConnectionError(包含所有连接相关错误)。
三、次要问题:URL 参数错误(双重t参数)
原因:
代码生成的 URL 是https://...?t=1762396363336?t=1762412374692,其中出现了两个?t=,这是错误的。URL 中多个参数应使用&连接,且时间戳参数只需一个(用于避免缓存)。
解决:
确保只添加一次时间戳参数
# 原错误代码(可能重复添加了t参数)
url = "https://airtw.moenv.gov.tw/json/AQI/Taiwan_2025110607.json?t=1762396363336"# 修正后(确保原始URL不带t参数,只添加一次)
url = "https://airtw.moenv.gov.tw/json/AQI/Taiwan_2025110607.json"
最后版本:可运行代码块:(报错的点修复之后)
import requests
import time
import json
from urllib3.exceptions import InsecureRequestWarning# 禁用SSL证书验证警告(可选,仅测试用)
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)# 目标URL(确保原始URL不带t参数)
url = "https://airtw.moenv.gov.tw/json/AQI/Taiwan_2025110607.json"
timestamp = int(time.time() * 1000)
url_with_ts = f"{url}?t={timestamp}" # 正确添加时间戳参数# 代理配置(替换为你的实际代理)
proxies = {"http": "http://127.0.0.1:7890","https": "http://127.0.0.1:7890"
}# 完整请求头
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36","Accept": "application/json, text/javascript, */*; q=0.01","Referer": "https://airtw.moenv.gov.tw/","X-Requested-With": "XMLHttpRequest"
}try:print("访问URL:", url_with_ts)response = requests.get(url_with_ts,headers=headers,proxies=proxies,timeout=20,verify=False # 临时关闭SSL验证(生产环境不建议))print(f"状态码: {response.status_code}")print(f"响应内容类型: {response.headers.get('Content-Type', '未知')}")print(f"原始响应(前500字符): {response.text[:500]}")# 解析JSON(返回的是列表,直接赋值给data)data = response.json()# 直接用len(data)获取列表长度(因为data是列表)print("✓ 连接成功!JSON解析成功,数据条数:", len(data))except json.JSONDecodeError as e:print(f"\n✗ JSON解析失败: {e}")
except requests.exceptions.ProxyError:print("\n✗ 代理错误:请检查代理地址和端口")
except ConnectionResetError: # 捕获内置的连接重置异常print("\n✗ 连接被服务器强制关闭:建议更换代理节点")
except requests.exceptions.ConnectionError: # 捕获其他连接错误print("\n✗ 网络连接错误:请检查代理是否正常")
except Exception as e:print(f"\n✗ 其他错误: {str(e)}")
