使用Playwright+Python上传CSV文件时遇ERR_H2_OR_QUIC_REQUIRED错误求助
问题:Playwright上传CSV时触发ERR_H2_OR_QUIC_REQUIRED错误
环境
Python + Playwright,运行于localhost:8000,使用Chrome浏览器有头模式
错误信息
上传CSV文件时控制台输出以下错误:
Failed to load resource: the server responded with a status of 404 (Not Found) for favicon.ico POST http://localhost:8000/upload - net::ERR_H2_OR_QUIC_REQUIRED Uncaught (in promise) TypeError: Failed to fetch at handleSubmit
相关代码
测试代码:
def test_response_format_and_values(): with sync_playwright() as playwright: browser = playwright.chromium.launch(headless=False) page = browser.new_page() upload_page = UploadPage(page) # 上传有效文件并点击上传按钮 response = upload_page.upload_file("valid_products.csv")
页面对象代码:
class UploadPage(BasePage): def upload_file(self, file_name: str) -> str: self.navigate("http://localhost:8000") file_path = str(CSV_FILE_PATH / file_name) self.page.set_input_files(self.file_input_selector, file_path) self.page.wait_for_selector(self.upload_button_selector) self.page.click(self.upload_button_selector) self.page.wait_for_selector(self.message_selector) results = self.page.text_content(self.message_selector) return results
已尝试操作
文件选择功能正常,但向/upload发送POST请求时因网络错误失败;试过多种上传方式以及ChatGPT给出的HTTP/2解决方案,均无效。
疑问
为什么会出现ERR_H2_OR_QUIC_REQUIRED错误?本地开发环境该怎么配置才能解决?
期望与实际行为
- 期望:CSV文件成功上传到本地服务器,返回JSON响应
- 实际:请求失败,触发
ERR_H2_OR_QUIC_REQUIRED和TypeError: Failed to fetch错误
问题原因及解决方案
错误原因
ERR_H2_OR_QUIC_REQUIRED表示浏览器要求使用HTTP/2或QUIC协议与服务器通信,但你的本地服务器可能仅支持HTTP/1.1,或者Chrome的配置强制要求使用更高版本协议。
解决步骤
调整服务器协议支持
确认本地服务器是否启用HTTP/2。如果服务器(如Flask、Django默认仅支持HTTP/1.1)不支持HTTP/2,可更换支持的服务器:- 若用Flask,使用
hypercorn替代内置服务器:pip install hypercorn hypercorn --bind localhost:8000 --workers 1 app:app - 若用Django,配置
daphne作为ASGI服务器来支持HTTP/2。
- 若用Flask,使用
修改Chrome启动参数
在Playwright启动Chrome时,添加禁用HTTP/2强制要求的参数,降级使用HTTP/1.1通信:browser = playwright.chromium.launch( headless=False, args=["--disable-http2"] )检查HTTPS配置
如果本地服务器使用自签名HTTPS证书,Chrome可能会强制要求HTTP/2。可暂时改用HTTP协议进行开发,或在Chrome中信任该自签名证书。重置浏览器网络配置
- 打开
chrome://net-internals/#h2,点击"Flush socket pools"清空连接池 - 进入
chrome://settings/resetProfileSettings重置Chrome网络设置
- 打开
内容的提问来源于stack exchange,提问作者BoazYashar
相关产品推荐
相关产品推荐

