码迷,mamicode.com
首页 > 其他好文 > 详细

模拟百度空间登录

时间:2015-03-04 14:49:02      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:

我的个人博客( 肥龙的博客)发表了新文章了!
欢迎大家过来阅读,以下是文章的连接地址

http://www.comingcode.com/?p=357


    由于自己有了个人的博客,但是又想提高点曝光率,所以就想到如何将自己的博客在其他网站曝光多点,当然最恶心的就是到每个网站或论坛上面发广告,这样不但可以增加曝光度,同样也能拉点仇恨。不管出于什么目的,如果是想在各个网站上手动一条条发的话,估计这个人也够忙的了。

    学习了python后,就可以实现自动将博客同步到别的网站上了,要做的只是模拟用户登录,然后再发送发表文章的请求。这里我只模拟了百度空间的登录和发布文章操作,其他一些网站的就后续再弄了。

    如果要问如何做到一个网站的模拟登录,那么就要知道怎么样获取一下登录操作的数据包,分析后,就用python模拟同样的数据包进行发送就可以了。常用的工具可以是google chrome、firefox等浏览器,又或者使用fiddler这样的专门监控http数据包的工具。总的一句就是,通过人工操作登录,同时使用工具监控发送和接收的数据包内容,通过分析后,就用python模拟同样格式的数据包。

    下面就贴出百度空间的模拟登录代码吧

    运行环境:python 2.7(3.x的没有测试过),windows or linux

    IDE工具:pycharm

    

# -*- coding:utf-8 -*-
"""
author: Dragon
date: 2015-01-02
"""

import cookielib
import urllib2
import urllib
import re

class BaiduSpace:
    def __init__(self):
        self.cookie = cookielib.LWPCookieJar()
        self.chandle = urllib2.HTTPCookieProcessor(self.cookie)

    #http get操作
    def getData(self, url, headers=None):
        request = None
        if headers is not None:
            request = urllib2.Request(url, headers=headers)
        else:
            request = urllib2.Request(url)

        request = urllib2.Request(url)
        opener = urllib2.build_opener(self.chandle)
        response = opener.open(request)
        data = response.read()
        try:
            data = data.decode(‘utf-8‘)
        except:
            data = data.decode(‘gbk‘,‘ignore‘)
        return data

    #http post操作
    def postData(self, url, data, header):
        data = urllib.urlencode(data);
        req = None
        if header is not None:
            req = urllib2.Request(url,data,headers=header)
        else:
            req = urllib2.Request(url,data)
        opener = urllib2.build_opener(self.chandle)
        response = opener.open(req)
        data = response.read()
        try:
            data = data.decode(‘utf-8‘).encode(‘utf-8‘)
        except:
            data = data.decode(‘gbk‘,‘ignore‘)
        return data

    #登录
    def login(self, name, pwd):
        #第一次先访问一下,目的是为了先保存一个cookie下来
        qurl = ‘https://passport.baidu.com/v2/api/?getapi&class=login&tpl=qing&tangram=false‘
        self.getData(qurl)

        #第二次访问,目的是为了获取token
        qurl = ‘https://passport.baidu.com/v2/api/?getapi&class=login&tpl=qing&tangram=false‘
        rsp = self.getData(qurl)

        login_tokenStr = ‘‘‘bdPass.api.params.login_token=‘(.*?)‘;‘‘‘
        login_tokenObj = re.compile(login_tokenStr,re.DOTALL)
        matched_objs = login_tokenObj.findall(rsp)
        if matched_objs:
            token = matched_objs[0]
            print ‘token =‘, token
            #然后用token模拟登陆
            post_data = {‘username‘:name,
                          ‘password‘:pwd,
                          ‘token‘:token,
                          ‘charset‘:‘UTF-8‘,
                          ‘callback‘:‘parent.bd__pcbs__1vwwr5‘,
                          ‘isPhone‘:‘false‘,
                          ‘mem_pass‘:‘on‘,
                          ‘logintype‘:‘basicLogin‘,
                          ‘logLoginType‘:‘pc_loginBasic‘,
                          ‘safeflg‘:‘0‘,
                          ‘staticpage‘:‘http://hi.baidu.com/com/show/proxy?for=v3_pass_login‘,
                          ‘tpl‘:‘qing‘,
                          ‘u‘:‘http://hi.baidu.com/go/login?from_page=0&from_mod=101‘,
                          ‘apiver‘:‘v3‘,
                          ‘quick_user‘:‘0‘,
                          ‘ppui_logintime‘:‘15118‘
                        }
            path = ‘http://passport.baidu.com/v2/api/?login‘
            headers = {
              "Accept": "image/gif, */*",
              "Referer": "https://passport.baidu.com/v2/?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2F",
              "Accept-Language": "zh-cn",
              "Content-Type": "application/x-www-form-urlencoded",
              "Accept-Encoding": "gzip, deflate",
              "User-Agent": "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)",
              "Host": "passport.baidu.com",
              "Connection": "Keep-Alive",
              "Cache-Control": "no-cache"
            }
            rsp = self.postData(path, post_data,headers)
            return True

        return False

    #创建文章
    def SendBlog(self, title, content, private=0):
        #获取bdstoken
        ret = self.getData(‘http://hi.baidu.com/pub/show/createtext‘);
        index = ret.find(‘https://passport.baidu.com?logout&bdstoken=‘)
        index2 = ret[index+len(‘https://passport.baidu.com?logout&bdstoken=‘):].find(‘&‘)
        if index == -1 or index2 == -1:
            return False

        bdstoken = ret[index+len(‘https://passport.baidu.com?logout&bdstoken=‘):index+len(‘https://passport.baidu.com?logout&bdstoken=‘)+index2]

        #构建发送的数据
        postTextData = {
                    ‘title‘ : title.encode("utf8"),
                    ‘content‘ : content.encode("utf8"),
                    ‘private‘: private,
                    ‘imgnum‘ : 0,
                    ‘bdstoken‘ : bdstoken,
                    ‘refer‘ : ‘http://hi.baidu.com/home‘,
                    ‘private1‘: private,
                    ‘qing_request_source‘: ‘new_request‘
                    }
        headers = {
                  "Accept": "*/*",
                  "Referer": "http://hi.baidu.com/pub/show/createtext",
                  "Accept-Language": "zh-CN,zh;q=0.8,en;q=0.6",
                  "Content-Type": "application/x-www-form-urlencoded",
                  "Accept-Encoding": "gzip, deflate",
                  "User-Agent": "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)",
                  "Connection": "Keep-Alive",
                  "Cache-Control": "no-cache",
                  ‘Origin‘:‘http://hi.baidu.com‘,
                  ‘X-Requested-With‘:‘XMLHttpRequest‘
                }

        retdata = self.postData(‘http://hi.baidu.com/pub/submit/createtext‘, postTextData, headers)


简单的测试代码:

if __name__ == ‘__main__‘:
    tBaidu = BaiduSpace()
    tBaidu.login(‘user_name‘,‘user_pwd‘) #这里填自己的帐号密码
    print "login baidu ..."

    for i in range(0, 5):
        title = "new title %d" % i
        content = "new content %d" % i
        tBaidu.SendBlog(title, content)
最后,我们能够看到自己的百度空间内多了几篇文章


模拟百度空间登录

标签:

原文地址:http://my.oschina.net/dragonblog/blog/382487

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!