所谓有状态的网页就是区别于传统html的动态交互式页面,它与用户进行交互显示不同的结果。下面我以新浪邮箱的登陆界面为例:
上面有一个用户登陆的表单,当我们输入正确地用户名密码之后,登陆成功转向邮箱操作窗口,否则给出错误信息。
使用mechanize库需要注意以下几个特点:
代码中要使用到mechanize库,如果没有安装的话可使用以下命令进行安装。
sudo pip install mechanize
I. 导入mechanize库,使用Browser()打开邮箱登陆页面。
>>>
>>> import mechanize
>>> br = mechanize.Browser()
>>>
>>> br.open(‘http://mail.sina.com.cn/‘)
< response_seek_wrapper at 0xb6c1eb2cL whose wrapped object = < closeable_response at 0xb6c2164cL whose fp = < socket._fileobject object at \0xb6c18b2c>>>
>>>
II. 列出网页中的表单。
>>>
>> for form in br.forms():
… print form
…
< POST http://mail.sina.cn/cgi-bin/sla.php?vt=3 application/x-www-form-urlencoded
< TextControl(local=)>
< SelectControl(domain=[*sina.com, sina.cn, 2008.sina.com, vip.sina.com])>
< PasswordControl(pwd=)>
< CheckboxControl(remember=[*1])>
< SubmitControl(=登录) (readonly)>>
>>>
III. 填写表单信息。
>>>
>>> br.select_form(nr=0)
>>> br.form[‘local’] = ‘pythontesting’
>>> br.form[‘pwd’] = ‘test*#123’
>>>
IV. 提交表单并查看返回代码
>>> br.submit()
< response_seek_wrapper at 0xb6c1eb8cL whose wrapped object = < closeable_response at 0x884ed8c whose fp = < socket._fileobject object at 0x881fb6c>>>
>>>
>>> print br.response().read()
从结果上看,已经成功登陆上去了。
I. 首先列出邮箱页面中含有的链接.
>>>
>> for link in br.links():
… print link.url + ‘:’+link.text
…
/basic/?sid=4840c2ea0c566e95ea5b3bbe224125586&vt=3:[IMG]
/basic/listmail.php?sid=4840c2ea0c566e95ea5b3bbe224125586&vt=3&fid=new:收信
/basic/writemail.php?sid=4840c2ea0c566e95ea5b3bbe224125586&vt=3:写信
/basic/findmail.php?sid=4840c2ea0c566e95ea5b3bbe224125586&vt=3:查找
/basic/listmail.php?sid=4840c2ea0c566e95ea5b3bbe224125586&vt=3&fid=new:收件夹(3)
/basic/listmail.php?sid=4840c2ea0c566e95ea5b3bbe224125586&vt=3&type=1&fid=all:未读邮件(3)
/basic/listmail.php?sid=4840c2ea0c566e95ea5b3bbe224125586&vt=3&fid=cur:草稿夹
/basic/listmail.php?sid=4840c2ea0c566e95ea5b3bbe224125586&vt=3&fid=out:已发送
/basic/listmail.php?sid=4840c2ea0c566e95ea5b3bbe224125586&vt=3&fid=subs:订阅邮件
/basic/listmail.php?sid=4840c2ea0c566e95ea5b3bbe224125586&vt=3&fid=tmp:已删除
/basic/listmail.php?sid=4840c2ea0c566e95ea5b3bbe224125586&vt=3&fid=unk:垃圾邮件
/basic/listmail.php?sid=4840c2ea0c566e95ea5b3bbe224125586&vt=3&fid=74:网站通知
/basic/listmail.php?sid=4840c2ea0c566e95ea5b3bbe224125586&vt=3&fid=75:订单账单
/basic/listmail.php?sid=4840c2ea0c566e95ea5b3bbe224125586&vt=3&fid=76:社交网络
/basic/listmail.php?sid=4840c2ea0c566e95ea5b3bbe224125586&vt=3&fid=77:订阅资讯
/basic/listmail.php?sid=4840c2ea0c566e95ea5b3bbe224125586&vt=3&fid=73:商讯信息
/basic/listmail.php?sid=4840c2ea0c566e95ea5b3bbe224125586&vt=3&fid=all:所有邮件(3)
/basic/logout.php?sid=4840c2ea0c566e95ea5b3bbe224125586&vt=3:退出
/basic/about.php?sid=4840c2ea0c566e95ea5b3bbe224125586&vt=3:帮助
>>>
II. 打开链接,跳转。
>>>
>>> new_link = br.click_link(text=’未读邮件(3)’)
>>>
>>> br.open(new_link)
< response_seek_wrapper at 0xb6c1e5ecL whose wrapped object = < closeable_response at 0x8853a8c whose fp = < socket._fileobject object at 0x881fdec>>>
>>>
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/jeanphorn/article/details/46917159