WFS地理数据导入:Chrome正常运行,Python遇SSL握手失败错误
问题描述
尝试获取目标GeoJSON文件,在Chrome或Safari中直接访问接口URL可正常显示JSON内容,但运行以下Python代码时出现SSL握手失败错误:
import requests import pathlib url = "https://geoserver.car.gov.br/geoserver/sicar/ows?service=WFS&version=2.0.0&request=GetFeature&count=10&startIndex=10000&typeName=sicar%3Asicar_imoveis_ac&outputFormat=application%2Fjson" r = requests.get(url, timeout=120, verify=False)
错误信息:
SSLError: HTTPSConnectionPool(host='geoserver.car.gov.br', port=443): Max retries exceeded with url: /geoserver/sicar/ows?service=WFS&version=2.0.0&request=GetFeature&count=10&startIndex=10000&typeName=sicar%3Asicar_imoveis_ac&outputFormat=application%2Fjson (Caused by SSLError(SSLError(1, '[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] ssl/tls alert handshake failure (_ssl.c:1006)')))
解决方案
这类错误通常是服务器要求的TLS版本/加密套件与requests默认配置不匹配导致的,浏览器会自动适配服务器支持的协议,但requests需要手动调整:
- 指定兼容的TLS版本
通过自定义适配器强制使用TLSv1.2(多数老服务器支持该版本):
import requests from requests.adapters import HTTPAdapter from urllib3.poolmanager import PoolManager import ssl class TLSAdapter(HTTPAdapter): def init_poolmanager(self, connections, maxsize, block=False): self.poolmanager = PoolManager( num_pools=connections, maxsize=maxsize, block=block, ssl_version=ssl.PROTOCOL_TLSv1_2 ) url = "https://geoserver.car.gov.br/geoserver/sicar/ows?service=WFS&version=2.0.0&request=GetFeature&count=10&startIndex=10000&typeName=sicar%3Asicar_imoveis_ac&outputFormat=application%2Fjson" session = requests.Session() session.mount("https://", TLSAdapter()) session.verify = False try: r = session.get(url, timeout=120) r.raise_for_status() print(r.json()) except requests.exceptions.RequestException as e: print(f"请求失败: {e}")
- 更新依赖库
旧版本的requests、urllib3可能缺少对新TLS协议的支持,执行以下命令更新:
pip install --upgrade requests urllib3 pyopenssl
- 模拟浏览器请求头
部分服务器会验证请求的User-Agent,添加浏览器标识可避免被拦截:
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" } r = session.get(url, timeout=120, headers=headers)
内容的提问来源于stack exchange,提问作者opposity
相关产品推荐
相关产品推荐

