Python3 simulation Baidu Login and realize Baidu Bar registration sample sharing (Baidu Bar automatic check-in) _python

Source: Internet
Author: User
Tags json urlencode

baiduclient.py

Copy Code code as follows:

Import Urllib.parse
Import gzip
Import JSON
Import re
From http.client import httpconnection
From htmlutils import Tiebaparser
Import Httputils as Utils

# Request Headers
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"] = ""

# cookies
cookies = List ()

# Personal Information
UserInfo = {}

DEF login (account, password):
' Login '
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)
# Login Success will return 302
return True if Resp.code = = 302 Else False

Def gettiebalist ():
' Get the list of the posted bars '
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):
    ' Get paste in sign-in information '
    querystr = Urllib.parse.urlencode ({"KW": tiebaname, "ie": "Utf-8", "T": 0.571444})
    conn = Httpconnection (" tieba.baidu.com
    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):
    ' sign in '
    # Get the parameters in the page TBS
    Conn1 = Httpconnection ("tieba.baidu.com")
    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]
     sign-in
    conn2 = httpconnection ("tieba.baidu.com")
    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 ():
' Get personal information '
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 ("Please enter accounts:")
Password = input ("Please enter password:")

OK = login (account, password)
If OK:
GetUserInfo ()
Print (userinfo["Data"] ["user_name_weak"] + "~ ~ ~ Login Successful", end= "\ \ \------\ n")
For TB in Gettiebalist ():
Print (TB + "bar:")
Signinfo = signin (TB)
If signinfo["no"]!= 0:
Print ("Check-in failed!")
Print (signinfo["error"])
Else
Print ("check-in successful!")
Print ("Check-in days:" + str (signinfo["Data"] ["Uinfo"] ["Cout_total_sing_num"])
Print ("Consecutive check-in days:" + str (signinfo["Data"] ["Uinfo"] ["Cont_sign_num"])
Print ("------")
Else
Print ("Logon Failed")

htmlutils.py

Copy Code code as follows:

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

Copy Code code as follows:

'''
Created on 2014-2-20

@author: Vincent
'''
def getcookiesfromheaders (headers):
"Get all cookies from the HTTP response"
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):
"' Save Cookies '"
For cookies in Cookies:
headers["Cookie"] = + cookie + ";"

def getcookievalue (Cookies, cookiename):
"Get the value of the specified cookie from the cookies"
For cookies in Cookies:
If cookiename in Cookie:
index = cookie.index ("=") + 1
Value = Cookie[index:]
return value

def parsequerystring (querystring):
' Parse query string '
result = Dict ()
STRs = Querystring.split ("&")
For S in STRs:
Name = S.split ("=") [0]
Value = S.split ("=") [1]
Result[name] = value
return result

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.