有时候我们需要像一个服务器POST数据。当然你用来模拟浏览器自动填写表单也是可以的。
先补一下知识
dictionary: 字典(即C++标准库的map)
dict = {‘ob1′:’computer’, ‘ob2′:’mouse’, ‘ob3′:’printer’}
每一个元素是pair,包含key、value两部分。key是Integer或string类型,value 是任意类型。
键是唯一的,字典只认最后一个赋的键值。
python脚本:
testpost.py
import urllib import urllib2 url = 'http://localhost/tools/testpost.php' values = {'obs_year':'2011','name':'Tom','sex':'Male'} #这是一个字典 data = urllib.urlencode(values) print data req = urllib2.Request(url, data) response = urllib2.urlopen(req) the_page = response.read() print the_page |
php脚本更简单(仅仅为了测试脚本的可用性)
tools/testpost.php
<?php print_r($_POST); ?> |
执行
name=Tom&obs_year=2011&sex=Male Array ( [name] => Tom [obs_year] => 2011 [sex] => Male ) |