python模拟登录及表单提交

  1. # -*- coding: utf-8 -*-  
  2. import re  
  3. import urllib  
  4. import urllib2  
  5. import cookielib  
  6. #获取CSDN博客标题和正文  
  7. url = "http://blog.csdn.net/[username]/archive/2010/07/05/5712850.aspx"  
  8. sock = urllib.urlopen(url)  
  9. html = sock.read()  
  10. sock.close()  
  11. content = re.findall('(?<=blogstory">).*(?=<p class="right artical)', html, re.S)  
  12. content = re.findall('<mce:script.*><!--  
  13. .*  
  14. // --></mce:script>(.*)', content[0], re.S)  
  15. title = re.findall('(?<=<title>)(.*)-.* - CSDN.*(?=</title>)', html, re.S)  
  16. #根据上文获取内容新建表单值  
  17. blog = {'spBlogTitle': title[0].decode('utf-8').encode('gbk'), #百度博客标题  
  18.         'spBlogText': content[0].decode('utf-8').encode('gbk'),#百度博客内容  
  19.         'ct'"1",  
  20.         'cm'"1"}  
  21. del content  
  22. del title  
  23. #模拟登录  
  24. cj = cookielib.CookieJar()  
  25. #用户名和密码  
  26. post_data = urllib.urlencode({'username''[username]''password''[password]''pwd''1'})  
  27. #登录路径  
  28. path = 'https://passport.baidu.com/?login'  
  29. opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))  
  30. opener.addheaders = [('User-agent''Opera/9.23')]  
  31. urllib2.install_opener(opener)  
  32. req = urllib2.Request(path, post_data)  
  33. conn = urllib2.urlopen(req)  
  34. #获取百度发布博客的认证令牌  
  35. bd = urllib2.urlopen(urllib2.Request('http://hi.baidu.com/[username]/creat/blog')).read()  
  36. bd = re.findall('(?<=bdstoken/" value=/").*(?=ct)', bd, re.S)  
  37. blog['bdstoken'] = bd[0][:32]  
  38. #设置分类名  
  39. blog['spBlogCatName'] = 'php'  
  40. #比较表单发布博客  
  41. req2 = urllib2.Request('http://hi.baidu.com/[username]/commit', urllib.urlencode(blog))  
  42. #查看表单提交后返回内容  
  43. print urllib2.urlopen(req2).read()  
  44. #请将[username]/[password]替换为您的真实用户名和密码  
  45. #搞定收工……  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值