0

我正在尝试使用 python cgi 和 webbrowser 模块从 html 表单提交操作中打开一个 url。我可以在 localhost 上启动 url, python -m webbrowser -t "http://myhost.com/path/to/some/file.html"但是 webbrowser.open(url, new=0, autoraise=True)在我的 cgi 脚本中,apache 提供一个空白页面,并且页面上没有打印任何错误。我的 Firefox 浏览器的位置框显示“ http://myhost.com/my_script.cgi?Submit=Submit ”而不是目标网址。

如果不能在这种情况下使用 webbrowser 模块,我对它的实际用途感到困惑。如果我使用 url 作为表单操作,页面将被提供给客户端,但我的脚本需要处理由以前的 html 表单传递的变量,以确定 url,然后将该 url 提供给客户端。让我知道我错过了什么,谢谢。

4

1 回答 1

0

我很确定,是的,您对 webbrowser 库应该做什么感到困惑。如果您在 cgi 中运行 webbrowser 命令,它将尝试在运行您的 cgi 脚本的服务器上打开一个 webbrowser(就像运行 cgi 的任何用户一样)。这可能行不通。我认为您希望发生的是您的 cgi 脚本应该将适当的 HTTP“命令”返回给浏览器以使其重定向。举个例子:

if "Submit" in form:
   url = "http://www.python.org #or do whatever processing is needed to calculate the new URL
   print "Status: 302" #this tells the browser the result is a redirect
   print "Location: " + url #this tells the browser where to redirect
   print "" #send two new lines to end the HTTP header

请注意,如果您使用的是 django 或其他库(我希望甚至只是 cgi 库计数),可能有更高级别的方法可以做到这一点,但这应该可以在任何地方使用。您还可以在 HTML 等中使用 META-refresh 执行操作。

于 2014-02-23T20:38:01.310 回答