python3模拟百度登录并实现百度贴吧签到示例分享(百度贴吧自动签到)


Posted in Python onFebruary 24, 2014

baiduclient.py

import urllib.parse
import gzip
import json
import re
from http.client import HTTPConnection
from htmlutils import TieBaParser
import httputils as utils
# 请求头
headers = dict()
headers["Connection"] = "keep-alive"
headers["Cache-Control"] = "max-age=0"
headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"
headers["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36"
headers["Content-Type"] = "application/x-www-form-urlencoded"
headers["Accept-Encoding"] = "gzip,deflate,sdch"
headers["Accept-Language"] = "zh-CN,zh;q=0.8"
headers["Cookie"] = ""
# cookie
cookies = list()
# 个人信息
userInfo = {}
def login(account, password):
    '''登录'''
    global cookies
    headers["Host"] = "wappass.baidu.com"
    body = "username={0}&password={1}&submit=%E7%99%BB%E5%BD%95&quick_user=0&isphone=0&sp_login=waprate&uname_login=&loginmerge=1&vcodestr=&u=http%253A%252F%252Fwap.baidu.com%253Fuid%253D1392873796936_247&skin=default_v2&tpl=&ssid=&from=&uid=1392873796936_247&pu=&tn=&bdcm=3f7d51b436d12f2e83389b504fc2d56285356820&type=&bd_page_type="
    body = body.format(account, password)
    conn = HTTPConnection("wappass.baidu.com", 80)
    conn.request("POST", "/passport/login", body, headers)
    resp = conn.getresponse()
    cookies += utils.getCookiesFromHeaders(resp.getheaders())
    utils.saveCookies(headers, cookies)
    # 登录成功会返回302
    return True if resp.code == 302 else False
    
def getTieBaList():
    '''获取已关注的贴吧列表'''
    conn = HTTPConnection("tieba.baidu.com", 80)
    conn.request("GET", "/mo/m?tn=bdFBW&tab=favorite", "", headers)
    resp = conn.getresponse()    
    tieBaParser = TieBaParser()
    tieBaParser.feed(resp.read().decode())
    tbList = tieBaParser.getTieBaList()
    return tbList
    
def getSignInfo(tieBaName):
    '''获取贴吧签到信息'''
    queryStr = urllib.parse.urlencode({"kw":tieBaName, "ie":"utf-8", "t":0.571444})
    conn = HTTPConnection("tieba.baidu.com", 80)
    conn.request("GET", "/sign/loadmonth?" + queryStr, "", headers)
    data = gzip.decompress(conn.getresponse().read()).decode("GBK")
    signInfo = json.loads(data)
    return signInfo
     
tbsPattern = re.compile('"tbs" value=".{20,35}"')
def signIn(tieBaName):
    '''签到'''
    # 获取页面中的参数tbs
    conn1 = HTTPConnection("tieba.baidu.com", 80)
    queryStr1 = urllib.parse.urlencode({"kw": tieBaName})
    conn1.request("GET", "/mo/m?" + queryStr1, "", headers)
    html = conn1.getresponse().read().decode()
    tbs = tbsPattern.search(html).group(0)[13:-1]
    # 签到
    conn2 = HTTPConnection("tieba.baidu.com", 80)
    body = urllib.parse.urlencode({"kw":tieBaName, "tbs":tbs, "ie":"utf-8"})
    conn2.request("POST", "/sign/add" , body , headers)
    resp2 = conn2.getresponse()
    data = json.loads((gzip.decompress(resp2.read())).decode())
    return data
    
def getUserInfo():
    '''获取个人信息'''
    headers.pop("Host")
    conn = HTTPConnection("tieba.baidu.com", 80)
    conn.request("GET", "/f/user/json_userinfo", "", headers)
    resp = conn.getresponse()
    data = gzip.decompress(resp.read()).decode("GBK")
    global userInfo
    userInfo = json.loads(data)

if __name__ == "__main__":
    account = input("请输入帐号:")
    password = input("请输入密码:") 
    ok = login(account, password)
    if ok:
        getUserInfo()
        print(userInfo["data"]["user_name_weak"] + "~~~登录成功", end="\n------\n")
        for tb in getTieBaList():
            print(tb + "吧:")
            signInfo = signIn(tb)
            if signInfo["no"] != 0:
                print("签到失败!")
                print(signInfo["error"])
            else:
                print("签到成功!")
                print("签到天数:" + str(signInfo["data"]["uinfo"]["cout_total_sing_num"]))
                print("连续签到天数:" + str(signInfo["data"]["uinfo"]["cont_sign_num"]))
            print("------") 
    else:
        print("登录失败")

htmlutils.py

'''
Created on 2014-2-20
@author: Vincent
'''
from html.parser import HTMLParser
class TieBaParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.tieBaList = list()
        self.flag = False
    def getTieBaList(self):
        return self.tieBaList
    def handle_starttag(self, tag, attrs):
        if tag == "a":
            for name , value in attrs:
                if name == "href" and "m?kw=" in value:
                    self.flag = True
    def handle_data(self, data):
        if self.flag:
            self.tieBaList.append(data)
            self.flag = False

httputils.py

'''
Created on 2014-2-20
@author: Vincent
'''
def getCookiesFromHeaders(headers):
    '''从http响应中获取所有cookie'''
    cookies = list()
    for header in headers:
        if "Set-Cookie" in header:
            cookie = header[1].split(";")[0]
            cookies.append(cookie)
    return cookies
def saveCookies(headers, cookies):
    '''保存cookies'''
    for cookie in cookies:
        headers["Cookie"] += cookie + ";"
def getCookieValue(cookies, cookieName):
    '''从cookies中获取指定cookie的值'''
    for cookie in cookies:
        if cookieName in cookie:
            index = cookie.index("=") + 1
            value = cookie[index:]
            return value
def parseQueryString(queryString):
    '''解析查询串'''
    result = dict()
    strs = queryString.split("&")
    for s in strs:
        name = s.split("=")[0]
        value = s.split("=")[1]
        result[name] = value
    return result
Python 相关文章推荐
python中常用的各种数据库操作模块和连接实例
May 29 Python
python实现数组插入新元素的方法
May 22 Python
Python作用域用法实例详解
Mar 15 Python
Python数组遍历的简单实现方法小结
Apr 27 Python
Python数据分析中Groupby用法之通过字典或Series进行分组的实例
Dec 08 Python
微信小程序跳一跳游戏 python脚本跳一跳刷高分技巧
Jan 04 Python
Python logging模块用法示例
Aug 28 Python
使用Python实现Wake On Lan远程开机功能
Jan 22 Python
Python抓新型冠状病毒肺炎疫情数据并绘制全国疫情分布的代码实例
Feb 05 Python
Python的pygame安装教程详解
Feb 10 Python
用Python实现童年贪吃蛇小游戏功能的实例代码
Dec 07 Python
python asyncio 协程库的使用
Jan 21 Python
python实现socket客户端和服务端简单示例
Feb 24 #Python
python抓取网页内容示例分享
Feb 24 #Python
使用python装饰器验证配置文件示例
Feb 24 #Python
python通过urllib2爬网页上种子下载示例
Feb 24 #Python
python控制台显示时钟的示例
Feb 24 #Python
python3访问sina首页中文的处理方法
Feb 24 #Python
python原始套接字编程示例分享
Feb 21 #Python
You might like
收音机发烧友应当熟知的100条知识
2021/03/02 无线电
五个PHP程序员工具
2008/05/26 PHP
php递归函数三种实现方法及如何实现数字累加
2015/08/07 PHP
PHP应用跨时区功能的实现方法
2019/03/21 PHP
Laravel5.1 框架Request请求操作常见用法实例分析
2020/01/04 PHP
做网页的一些技巧
2007/02/01 Javascript
锋利的jQuery 要点归纳(一) jQuery选择器
2010/03/21 Javascript
javascript作用域容易记错的两个地方分析
2012/06/22 Javascript
JS实现鼠标经过好友列表中的好友头像时显示资料卡的效果
2014/07/02 Javascript
js实现飞入星星特效代码
2014/10/17 Javascript
JavaScript中的逻辑判断符&&、||与!介绍
2014/12/31 Javascript
JavaScript中instanceof运算符的使用示例
2016/06/08 Javascript
vue2.0结合DataTable插件实现表格动态刷新的方法详解
2017/03/17 Javascript
angularJS开发注意事项
2018/05/26 Javascript
JS栈stack类的实现与使用方法示例
2019/01/31 Javascript
使用Node.js实现一个多人游戏服务器引擎
2019/03/13 Javascript
你不可不知的Vue.js列表渲染详解
2019/10/01 Javascript
详细讲解用Python发送SMTP邮件的教程
2015/04/29 Python
Python字符串替换实例分析
2015/05/11 Python
python常用知识梳理(必看篇)
2017/03/23 Python
分享几道你可能遇到的python面试题
2017/07/24 Python
python调用虹软2.0第三版的具体使用
2019/02/22 Python
对Python 简单串口收发GUI界面的实例详解
2019/06/12 Python
解决python flask中config配置管理的问题
2019/07/26 Python
python ftplib模块使用代码实例
2019/12/31 Python
Jupyter notebook快速入门教程(推荐)
2020/05/18 Python
使用Python文件读写,自定义分隔符(custom delimiter)
2020/07/05 Python
在css3中background-clip属性与background-origin属性的用法介绍
2012/11/13 HTML / CSS
size?丹麦官网:英国伦敦的球鞋精品店
2019/04/15 全球购物
俄罗斯连接商品和买家的在线平台:goods.ru
2020/11/30 全球购物
大学生蛋糕店创业计划书
2014/01/13 职场文书
高校十八大报告感想
2014/01/27 职场文书
质量安全标语
2014/06/07 职场文书
高中生第一学年自我鉴定
2014/09/12 职场文书
2014年大学生工作总结
2014/11/20 职场文书
Python 实现绘制子图及子图刻度的变换等问题
2021/05/31 Python