使用Linux命令行提交表单和上传文件
我需要在Linux命令行中向一个网站提交表单和上传文件。
我查了一些资料,想用Python来写这个脚本。
首先,我需要登录这个网站,保存登录时的cookies,然后再提交表单数据和上传文件。
具体情况如下:
这个网站的登录页面是:hxxp://www.example.com/login.html
<form action="/signin.html" method="post">
Username:<input type="text" name="username">
Password:<input type="password" name="password">
<input type="hidden" name="referer" value="http://www.example.com/">
<input type="submit" name="submit" value=" Login ">
</form>
上传页面是:hxxp://www.example.com.com/upload/
<form action="http://www.example.com:81/upload/upload.cgi" enctype="multipart/form-data" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="314572800" />
File:
<input name="filename[]" type="file" />
Type:
<input type="radio" name="typeID" value=1> Option One
<input type="radio" name="typeID" value=2> Option Two
<input type="radio" name="typeID" value=3> Option Three
Title:
<input type="text" name="title" >
Description:
<textarea name="description"></textarea>
<input type="checkbox" name="agree" value="agree_terms"> I Accept Terms
<input type="submit" value="Upload It!">
</form>
这个表单里有单选框、文本框、复选框、文件等输入项。
请给我一些提示!
我使用的是CentOS 5.5,已经安装了Python、wget和PHP。我觉得可以用Python脚本来完成这个任务。
非常感谢!你的回答将是我收到的最好的圣诞礼物。;)
1 个回答
2
当然,你可以使用 urllib2
来完成这个任务。你可以查看相关文档,了解如何处理 cookies 和如何上传文件。不过,我觉得使用 mechanize
会省下很多时间。Mechanize 让你可以像使用浏览器一样处理网页:
import mechanize
br = mechanize.Browser()
br.open("http://www.example.com/")
br.select_form()
br['username'] = 'user'
br['password'] = 'pass'
br.submit()
etc.