国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python3模擬百度登錄并實現(xiàn)百度貼吧簽到示例分享(百度貼吧自動簽到)

2019-11-25 18:30:20
字體:
供稿:網(wǎng)友

baiduclient.py

復(fù)制代碼 代碼如下:

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():
    '''獲取已關(guān)注的貼吧列表'''
    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):
    '''簽到'''
    # 獲取頁面中的參數(shù)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("簽到天數(shù):" + str(signInfo["data"]["uinfo"]["cout_total_sing_num"]))
                print("連續(xù)簽到天數(shù):" + str(signInfo["data"]["uinfo"]["cont_sign_num"]))
            print("------")
    else:
        print("登錄失敗")

htmlutils.py

復(fù)制代碼 代碼如下:

'''
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

復(fù)制代碼 代碼如下:

'''
Created on 2014-2-20

@author: Vincent
'''
def getCookiesFromHeaders(headers):
    '''從http響應(yīng)中獲取所有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

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 大同县| 南郑县| 莱西市| 威信县| 舒兰市| 敖汉旗| 田阳县| 宁都县| 钟祥市| 重庆市| 兰溪市| 星子县| 樟树市| 通榆县| 宽城| 南木林县| 册亨县| 孝感市| 松江区| 筠连县| 崇明县| 松溪县| 济宁市| 长泰县| 禹城市| 鄂温| 南充市| 桐柏县| 青海省| 黑龙江省| 那坡县| 北宁市| 佛学| 师宗县| 友谊县| 泸定县| 阳原县| 民丰县| 灌南县| 武夷山市| 桐乡市|