python3模拟百度登录并实现百度贴吧签到示例分享(百度贴吧自动签到)
发布时间:2023-07-08 23:15:23
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
猜你喜欢
- 0. 学习目标单链表只有一个指向直接后继的指针来表示结点间的逻辑关系,因此可以方便的从任一结点开始查找其后继结点,但要找前驱结点则比较困难,
- 背景Python 作为一门成熟的编程语言,拥有无数优秀的第三方包以方便开发者能够快速地构建应用。一般来说,如果你开发了一个 Python 软
- 经过了上个星期的努力学习,对处理html又有了新的发现感觉真的很不错可以说js的威力在处理html代码方面我又有所领悟了1、截取特定长度字符
- 解决golang编译提示dial tcp 172.217.160.113:443: connectex: A connection atte
- <script type="text/javascript">/*<![CDAT
- 原始数据如下:['e3cd', 'e547', 'e63d', '0ffd'
- python 类的继承对于许多文章讲解python类的继承,大多数都是说一些什么oop,多态等概念,我认为这样可能对有一定基础的开发者帮助不
- 小试牛刀:1.需要python如何读取文件2.需要python操作list3.需要使用split()对字符串进行分割代码运行截图 :代码(c
- 1. 引言在Python开发中,itertools库经常被忽视,实际上该库中抱恨了一些非常棒的函数,特别是用于处于数据流的函数。在本文中,我
- 一、关于m3u8:m3u8是苹果公司推出一种视频播放标准,是m3u的一种,不过编码方式是utf-8,是一种文件检索格式,将视频切割成一小段一
- Microsoft建立了一种既灵活又强大的安全管理机制,它能够对用户访问SQL Server服务器系统和数据库的安全进行全面地管理。按照本文
- 经常有需要扫描目录,对文件做批量处理的需求,所以对目录处理这块做了下学习和总结。Python 中扫描目录有两种方法:os.listdir 和
- 从 Python 3 开始,str 类型代表着 Unicode 字符串。取决于编码的类型,一个 Unicode 字符可能会占 4 个字节,这
- 前言:NumPy 是 Python 语言的一个扩充程序库,支持大量高维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库。同时NumP
- 提到开心消消乐这款小游戏,相信大家都不陌生,其曾在 2015 年获得过玩家最喜爱的移动单机游戏奖,受欢迎程度可见一斑,本文我们使用 Pyth
- char、varchar、text和nchar、nvarchar、ntext的区别1、CHAR。CHAR存储定长数据很方便,CHAR字段上的
- 么是约瑟夫问题?约瑟夫问题是一个有趣的数学游戏,游戏规则如下:1、N个人围成一个圈,编号从1开始,依次到N。2、编号为M的游戏参与者开始报数
- 模板的继承完美在写html的时候会发现,自己多个html文件中又好多东西是一样的,包括静插件的引入 还有有些简单的css样式都不需要修改,这
- 自动弹出窗口是一个让人讨厌的事情,为什么我们用它来显示我们的调查表呢?用弹出窗口来显示调查表,被认为是达到我们收集访问用户信息的最方便快捷的
- 之前给大家介绍过python高手之路python处理excel文件(方法汇总) Python操作Excel之xlsx文件&nbs