Python实现模拟登录及表单提交的方法

yipeiwu_com7年前Python基础

本文实例讲述了Python实现模拟登录及表单提交的方法。分享给大家供大家参考。具体实现方法如下:

# -*- coding: utf-8 -*- 
import re 
import urllib 
import urllib2 
import cookielib 
#获取CSDN博客标题和正文 
url = "http://blog.csdn.net/[username]/archive/2010/07/05/5712850.aspx" 
sock = urllib.urlopen(url) 
html = sock.read() 
sock.close() 
content = re.findall('(?<=blogstory">).*(?=<p class="right artical)', html, re.S) 
content = re.findall('<script.*>.*</script>(.*)', content[0], re.S) 
title = re.findall('(?<=<title>)(.*)-.* - CSDN.*(?=</title>)', html, re.S) 
#根据上文获取内容新建表单值 
blog = {'spBlogTitle': title[0].decode('utf-8').encode('gbk'), #百度博客标题 
    'spBlogText': content[0].decode('utf-8').encode('gbk'),#百度博客内容 
    'ct': "1", 
    'cm': "1"} 
del content 
del title 
#模拟登录 
cj = cookielib.CookieJar() 
#用户名和密码 
post_data = urllib.urlencode({'username': '[username]', 'password': '[password]', 'pwd': '1'}) 
#登录路径 
path = 'https://passport.baidu.com/?login' 
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) 
opener.addheaders = [('User-agent', 'Opera/9.23')] 
urllib2.install_opener(opener) 
req = urllib2.Request(path, post_data) 
conn = urllib2.urlopen(req) 
#获取百度发布博客的认证令牌 
bd = urllib2.urlopen(urllib2.Request('http://hi.baidu.com/[username]/creat/blog')).read() 
bd = re.findall('(?<=bdstoken\" value=\").*(?=ct)', bd, re.S) 
blog['bdstoken'] = bd[0][:32] 
#设置分类名 
blog['spBlogCatName'] = 'php' 
#比较表单发布博客 
req2 = urllib2.Request('http://hi.baidu.com/[username]/commit', urllib.urlencode(blog)) 
#查看表单提交后返回内容 
print urllib2.urlopen(req2).read() 
#请将[username]/[password]替换为您的真实用户名和密码

希望本文所述对大家的Python程序设计有所帮助。

相关文章

python实现中文文本分句的例子

对于英文文本分句比较简单,只要根据终结符"."划分就好,中文文本分句看似很简单,但是实现时会遇到很多麻烦,尤其是处理社交媒体数据时,会遇到文本格式不规范等问题。 下面代码针对一段一段的短...

python下读取公私钥做加解密实例详解

python下读取公私钥做加解密实例详解 在RSA有一种应用模式是公钥加密,私钥解密(另一种是私钥签名,公钥验签)。下面是Python下的应用举例。 假设我有一个公钥文件,rsa_pub...

selenium+python自动化测试环境搭建步骤

selenium+python自动化测试环境搭建步骤

相对于自动化测试工具QTP来说,selenium小巧、免费,而且兼容Google、FireFox、IE多种浏览器,越来越多的人开始使用selenium进行自动化测试。 我是使用的pyth...

Python遍历pandas数据方法总结

Python遍历pandas数据方法总结

前言 Pandas是python的一个数据分析包,提供了大量的快速便捷处理数据的函数和方法。其中Pandas定义了Series 和 DataFrame两种数据类型,这使数据操作变得更简...

pandas.cut具体使用总结

用途 pandas.cut用来把一组数据分割成离散的区间。比如有一组年龄数据,可以使用pandas.cut将年龄数据分割成不同的年龄段并打上标签。 原型 pandas.cut(x,...