代码之家  ›  专栏  ›  技术社区  ›  Martin

如何使用python加载向URL发布值的浏览器会话?

  •  1
  • Martin  · 技术社区  · 14 年前

    我有一个python脚本,它接受许多变量。我还有一个HTML页面可以接收post值。

    如何从python启动浏览器并将其指向上面的html页面,并将这些post变量发送到html url?

    我的问题是,如果我使用urllib/urllib2来发布,它就不会加载浏览器窗口。如果我想加载一个浏览器窗口,我就不能向该URL发送帖子。

    这就是你如何向一个URL发帖,但它不能打开浏览器,相反它可以接收这样的返回值。但我不需要读取值,我需要打开一个Internet浏览器,将其指向一个特定的URL,并将变量发布到该URL。

    data = urllib.urlencode({"fileTitle" : "ThisFileName", "findtype" : "t", "etc" : "etc"})
    f = urllib.urlopen("http://www.domain.com/someurl/", data)
    # Read the results back.
    s = f.read()
    s.close()
    
    3 回复  |  直到 14 年前
        1
  •  0
  •   Vortura    14 年前

    这些值必须通过HTTP POST提供吗?您可以提供参数作为URL的一部分并使用get来代替吗?

    例如,构建类似以下内容的URL:

    http://somehost/somefile.html?param1=value1&param2=value2&

        2
  •  0
  •   kschaper    14 年前

    “……”它不会加载浏览器窗口。“

    对不起,我不完全理解你想做什么。但也许硒遥控器(RC)对你来说很有趣。您可以编写脚本来远程控制浏览器。它用于自动测试。也支持python。您可以让浏览器提交表单或单击链接,例如到PHP脚本或其他。

        3
  •  0
  •   Martin    14 年前

    这似乎是我想做的唯一方法。

    可以使用urllib调用服务器上存储数据(在SQL表或临时文件中)并返回唯一ID的页。然后可以使用唯一ID从其已知源获取该数据。

    python代码将如下所示:

    import urllib
    data = urllib.urlencode({"postField1" : "postValue1", "postField2" : "postValue2", "etc" : "etc"})
    f = urllib.urlopen("http://www.domain.com/storePostData.php", data)
    # At this point your storePostData.php file stores all the post 
    # info in either an sql DB or temporary file so this can accessed later on and
    # an uuid is passed back which we now read below. In may case I store all post        
    # fields in a sql DB and each column represents each post field.
    uuid = f.read()
    # the uuid is the sql table id field which is auto_incremented.
    # SO now we load the default browser below and send it the uuid so the php script
    # can access the sql data. Once it has been accessed and the form fields have been 
    # received then we delete that row as the information is useless to us now that we 
    # have filled in the forms fields
    import webbrowser
    webbrowser.open_new("http://www.domain.com/someOtherUrl?uuid=" + uuid)
    

    其余的工作都是由PHP脚本完成的,在那里它存储信息,然后根据UUID检索信息。我不打算在这里举一个代码的例子,因为这只是一般的知识,我所要做的就是把这个概念带到这里。

    我希望这能帮助别人。

    干杯