You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python webbrowser打开请求返回内容时出现文件未找到错误

解决Python中用webbrowser打开请求返回的HTML内容报错问题

用Postman发送GET请求时,选择“发送并下载”得到的HTML文件可以在浏览器正常打开执行,但用以下Python代码尝试实现相同功能时,浏览器提示“文件未找到”:

from requests import get as GET
import webbrowser

tokenUrl = '...'
tokenParams = {}
r = GET(tokenUrl,params = tokenParams)
print(r.text)
webbrowser.open(r.text)

错误信息

Firefox can’t find the file at currentpath/

问题原因

webbrowser.open() 方法只接受URL地址或本地文件路径作为参数,你直接传入请求返回的HTML文本内容,浏览器会把这段文本当作本地文件路径去查找,自然找不到对应文件,因此报错。

解决方案

方案1:将HTML内容保存为本地临时文件后打开

模拟Postman“发送并下载”的逻辑,把HTML内容写入临时文件,再让浏览器打开该文件:

from requests import get as GET
import webbrowser
import tempfile
import os

tokenUrl = '...'
tokenParams = {}
r = GET(tokenUrl, params=tokenParams)

# 创建临时HTML文件
with tempfile.NamedTemporaryFile(mode='w', suffix='.html', delete=False) as f:
    f.write(r.text)
    temp_file_path = f.name

# 打开临时文件
webbrowser.open(f'file://{os.path.abspath(temp_file_path)}')

# 可选:若不需要保留文件,可在打开后删除
# os.unlink(temp_file_path)

方案2:直接提取HTML中的跳转URL打开

从返回的HTML内容可以看到,页面包含自动跳转至Salesforce登录页的逻辑,直接提取该URL打开更高效:

from requests import get as GET
import webbrowser
import re

tokenUrl = '...'
tokenParams = {}
r = GET(tokenUrl, params=tokenParams)

# 用正则提取跳转URL
match = re.search(r"handleRedirect\('(.*?)'\)|location.replace\('(.*?)'\)|location.href ='(.*?)'", r.text)
if match:
    redirect_url = match.group(1) or match.group(2) or match.group(3)
    if redirect_url:
        webbrowser.open(redirect_url)

内容的提问来源于stack exchange,提问作者Harsh Prakash Agarwal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 17:50:37