我尝试使用Python和HTTP请求在随机网站上传文件。为此,我使用名为Requests的方便库。
根据the documentation以及StackOverflow here和there上的一些答案,我只需要在我的应用程序中添加files
参数,然后再研究它的DOM网页。
方法很简单:
有时这很好用。实际上,我设法在此网站上传了一个文件:http://pastebin.ca/upload.php
查看源代码后,表单的网址为upload.php
,按钮名称为file
和s
,值为Upload
,所以我得到了以下代码:
url = "http://pastebin.ca/upload.php"
myFile = open("text.txt","rb")
r = requests.get(url,data={'s':'Upload'},files={'file':myFile})
print r.text.find("The uploaded file has been accepted.")
# ≠ -1
但现在,让我们看一下该网站:http://www.pictureshack.us/
相应的代码如下:
url = "http://www.pictureshack.us/index2.php"
myFile = open("text.txt","rb")
r = requests.get(url,data={'Upload':'upload picture'},files={'userfile':myFile})
print r.text.find("Unsupported File Type!")
# = -1
事实上,我在这两个网站之间看到的唯一区别是,对于第一个,提交表单时完成工作的URL与表单所在的页面和文件的上载位置相同。 / p>
但这并没有解决我的问题,因为我仍然不知道如何在第二种情况下提交我的文件。
我试图在主页上而不是.php上发出请求,但当然它不起作用。
另外,我有另一个问题。
假设某些表单元素没有“name”属性。我应该如何根据我的要求用Python指定它?
例如,此网站:http://imagesup.org/
提交表单按钮如下所示:<input type="submit" value="Héberger !">
如何在数据参数中使用它?
答案 0 :(得分:1)
表单包含您必须遵守的另一个组件:method
属性。您正在使用GET
个请求,但您引用的表单使用method="post"
。使用requests.post
发送POST
请求。