简体   繁体   English

将数据发布到Web进行处理

[英]post data to web for processing

I am a newbie to web development, so please be mercy if the following question sounds a bit naive. 我是Web开发的新手,因此,如果以下问题听起来有些天真,请保持谨慎。 How can I post to a web form using python? 如何使用python发布到Web表单? I know the web form is something like this, and I want to upload a local file for it to be processed online and get the returned data 我知道Web表单是这样的,我想上传一个本地文件以便在线处理并获取返回的数据

<form action="process.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file" id="file" id="chooser" /><br />
    <input type="submit" value="Upload" name="submit"  />
</form>

Here's what I have for my python program so far. 到目前为止,这是我为python程序准备的内容。

upfile = urllib.urlencode( {'file':path/to/my/local/file})
filehandle = urllib.urlopen('http://www.comdroid.org/', upfile)
soup = BeautifulSoup(filehandle)
print soup

I want to see the returned results, but the current code snippet only gives me the result without processing my uploaded file. 我想查看返回的结果,但是当前的代码片段仅给出了结果,而没有处理上传的文件。 Is there anything I am missing 有什么我想念的吗

------------UPDATE---------------- Here is how I do it now ------------ UPDATE ----------------这是我现在的做法

import urllib2
import urllib 
import requests
import os
files1 ={'file':open('/opt/apps/au.com.psyborg.sbc-5.apk','rb')‌​}
#response= os.system("curl --form   file=@/opt/apps/au.com.psyborg.sbc-5.apk --form submit=Upload www.comdroid.org/process.php")
req = requests.post('comdroid.org/process.php', files = files1) 
print req.text

The weird thing is I cannot do it with request, the server complains my file is not .apk file, which it actually is. 奇怪的是我无法处理请求,服务器抱怨我的文件不是.apk文件,实际上是。 But if I switch to curl using os.system as commented out, it works! 但是,如果我使用注释掉的os.system切换到curl,它将起作用! So I doubt I am missing something here in request. 所以我怀疑我是否在要求中缺少某些东西。 Any suggestion? 有什么建议吗?

If you look at the form's action property, it's going to process.php - so you'll need to send your file upload to http://www.comdroid.org/process.php . 如果您查看表单的action属性,它将进入process.php因此需要将文件上传发送到http://www.comdroid.org/process.php

Doing file uploads with the standard library is a bit of a pain - if you're allowed to, I would recommend using requests for this - they even have an example of what you're asking for in their documentation : 使用标准库上传文件有点麻烦-如果允许的话,我建议使用对此的请求 -他们甚至在其文档中都提供了您所要求的示例

url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)

I also found this SO answer on how to do it with the mechanize library , and a code sample that might help if you want to do it with the standard library . 我还找到了有关如何使用机械化库执行此操作的答案 ,以及一个代码示例,如果您想使用标准库进行操作,则可能会有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM