Python: Sina Weibo API usage and secure analog login automatically get code value __python

Source: Internet
Author: User
Tags base64 urlencode ticket

has been using analog landing methods to obtain micro-blog data. Suddenly feel good old-fashioned, the most important thing is, Soga, good slow. So explore the use of the API, experience the feeling of tall.

Author @ Liu Xuefeng contributed to the SDK. Demo is out of the truth, practice. Don't say much nonsense. Begin. 1. API download and application creation

Microblogging API Home Address: Click on the Open link.

1, the first to fill out the personal developer or enterprise development information. Time too long, this is not a difficult point, not detailed.

2, the following start to create applications, I chose the station application. This is also very simple.


3, download the corresponding SDK, I use Python. Install, if the error, please copy weibo.py directly to your project directory. Another file does not know how to use (14.05.21 Note, always updated).

SDK Download Address: Click on the Open link.

4, use, reference article: Sina Weibo API use of the Python interface of the use of the author @monsion

#!/usr/bin/python 
#-*-coding:utf-8-*-""
# Microblogging API Test "" "
import sys 
reload (SYS)
Sys.setdefaultencoding ("UTF8")

from Weibo import apiclient

import mysqldb, webbrowser
import urllib3

if __name__ = = "__main__":
    App_key = U ' # app KEY
    app_secret = U ' # app SECRET
    callback_url = ' http://apps.weibo.com/zhanhisnshows '
    Client = Apiclient (App_key=app_key, App_secret=app_secret, redirect_uri=callback_url)
    URL = client.get_ Authorize_url ()
    print URL
    webbrowser.open_new (URL)
App_key and App_secret will be created after the application, the key is callback_url how to obtain.

Fill in a random callback_url error:


The reason is callback_url fill in the wrong.

So Baidu, decisive, find the information is useless. It's all about the place to fill out the map.


Try it. So I tried to fill in the application data. Fill in the station application address, fix. As shown in the following illustration:


The final result is the 34th diagram. Get code succeeded.

(2014.05.21 Note: Today I found the tutorial, why I did not find a pinch when needed.) Reference: Sina Weibo API usage preliminary introduction--solve the problem of callback address author @monsion


The value of the code is in the Address bar. Next you start getting the data.

(2014. 05.21 Note: Bo Master play play will fall to the automatic access code pit, data acquisition slowly, later update ... 2. Automatically get code value Bo master himself slowly pondering, the middle get key parameters ticket encountered problems, the problem is as follows: question 1: Error: URLLIB2. Urlerror: <urlopen error unknown URL type:https>

Solution: Many say is not installed OPEMSSL, I have installed, or error. Finally found the reason is: URL error ... I went, totally screwed up, and it looked right, but when I copied it to the browser I found something in front of HTTPS, which was this, for a couple of hours.

Okay, there's nothing wrong with that. Need to remind everyone is: Pcid, Servertime, nonce, rsakv, SP, su parameters of the acquisition, involving analog landing, if not, you can refer to my Sina blog article: Python sina Weibo analog landing & Password encryption analysis can not read the blog message or microblogging @the_third_wave.

Bo Master Finish ticket, start the final battle, success.

which has reference Python call Sina Weibo API practice @ Pop Shadow

Download the @ Pop shadow of the code, run OK, found the problem. In the @ Pop shadow code, the user name and password are transmitted in plaintext, so rewrite the code as follows, and welcome the criticism:

#!/usr/bin/python #-*-Coding:utf-8-*-"" [Filename] weiboapi.py @author: U{the_third_wave/huan Zhan<mailto:zhan 
h121823 at Sina.com&gt. @copyright: U{copyright (c) 2014.05.22, Huan Zhan} @contact: zhanh121823 at sina.com/qq:563134080  @version: $1.0$ # Microblogging API Interface "" "Import sys reload (SYS) sys.setdefaultencoding (" UTF8 ") from Weibo import apiclient import

MySQLdb, WebBrowser, RE, JSON import Urllib, URLLIB2, URLLIB3, cookielib import Hashlib, base64, RSA, BINASCII # Encrypt Class Smartredirecthandler (Urllib2.
    Httpredirecthandler): "" "# Reference: Pop Shadow/blog:http://www.cnblogs.com/wly923/archive/2013/04/28/3048700.html" "" Def http_error_301 (CLS, req, FP, code, MSG, headers): result = Urllib2.

    httpredirecthandler.http_error_301 (CLS, req, FP, code, MSG, headers) Result.status = code return result Def http_error_302 (CLS, req, FP, code, MSG, headers): result = Urllib2.
 httpredirecthandler.http_error_302 (CLS, req, FP, code, MSG, headers)       Result.status = code return result def get_cookie (): cookies = cookielib. Cookiejar () return URLLIB2. Httpcookieprocessor (Cookies) def get_opener (proxy=false): Rv=urllib2.build_opener (Get_cookie (), Smartredirecthandl ER ()) rv.addheaders = [(' User-agent ', ' mozilla/4.0 ') (compatible; MSIE 6.0; Windows NT 5.1; SV1)] Return to RV class Sinaapi (): "" "# @author: U{the_third_wave/huan zhan<mailto:zhanh121823 at SINA.C The Om&gt} # Get_code_ns () method is written by the popular shadow. /blog:http://www.cnblogs.com/wly923/archive/2013/04/28/3048700.html # Get_code_ns () plaintext transmission password, unsafe. So the author @the_third_wave to obtain the important parameter ' ticket ' by simulating the landing method. To ensure that the transmission process of unknown messaging password.
    Ensure safety.
    The # Get_code_security () method is a method for the author to automatically obtain code for the @the_third_wave write.
    # in doubt, please blog:http://blog.csdn.net/zhanh1218/article/details/26383469 message or Sina Weibo focus on the author @the_third_wave. "" Def __init__ (self, callback_url, App_key, Redirect_url, user_id, user_pswd): self. Callback_url = Callback_url self. App_key = App_key SELf. Redirect_url = Redirect_url self. user_id = user_id self. USER_PSWD = user_pswd Self.http = urllib3. Poolmanager () def get_username (self, user_id): # The encryption algorithm of username # Ssol
        Ogin.js:ah.su=sinassoencoder.base64.encode (M (AJ)); User_id_ = Urllib.quote (user_id) # encode username, avoid error example:@ & su = base64.encodestring (user_id _) [: -1] return su def get_password_rsa (self, user_pswd, PubKey, Servertime, nonce): # Cryptographic encryption Operation Sina I have
        There are two kinds of knowledge, and this is one of them. # RSA Encrypt: #when pwencode = "RSA2" rsapubkey = Int (PubKey,) #pubkey from key_1 = Int (' 100 #10001 to 65537 key = RSA.  PublicKey (Rsapubkey, key_1) # message = str (servertime) + "\ T" + str (nonce) + "\ n" + str (USER_PSWD) passwd = Rsa.encrypt (message, key) passwd = Binascii.b2a_hex (passwd) #to return passwd def get_par
   Ameter (self):     Su = Self.get_username (self. USER_ID) #su = get_username (user_id) url = "Https://login.sina.com.cn/sso/prelogin.php?entry=openapi&c Allback=sinassocontroller.prelogincallback\ &su= "+su+" &rsakt=mod&checkpin=1&client=ssologin.js ( v1.4.15) "R = self.http.request (' Get ', url) p = re.compile (' (. *)") Json_data = P.search (r.data
        ). Group (1) data = Json.loads (json_data) PubKey = data[' PubKey '] pcid = data[' Pcid '] Servertime = str (data[' servertime ']) nonce = data[' nonce '] rsakv = str (data[' rsakv ']) sp = self . Get_password_rsa (self. USER_PSWD, PubKey, Servertime, nonce) #print pcid; Print servertime; Print nonce; Print rsakv; Print SP; Print Su return pcid, Servertime, nonce, rsakv, SP, su def get_ticket (self): Pcid, Servertim E, nonce, rsakv, sp, su = Self.get_parameter () fields = Urllib.urlencode ({' EntRy ': ' Openapi ', ' Gateway ': ' 1 ', ' from ': ', ' savestate ': ' 0           ', ' useticket ': ' 1 ', ' pagerefer ': ', ' pcid ': pcid, ' CT '
            : ' 1800 ', ' s ': ' 1 ', ' VSNF ': ' 1 ', ' vsnval ': ', ' Door ': ', ' appkey ': ' kxr5r ', ' su ': su, ' service     ': ' Miniblog ', ' servertime ': servertime, ' nonce ': nonce, ' Pwencode ' : ' Rsa2 ', ' rsakv ': rsakv, ' SP ': SP, ' sr ': ' 1680*1050 '
            , ' Encoding ': ' UTF-8 ', ' cdult ': ' 2 ', ' domain ': ' weibo.com ', ' Prelt ': ' 0 ', ' returntype ': ' TEXT ',} ' headers = {# ' request ': "Post/sso/login.php?cliEnt=ssologin.js (v1.4.15) &_=1400652171542 http/1.1 ", #" Accept ":" */* "," content- Type ': ' application/x-www-form-urlencoded ', # ' Referer ': self.
                   Callback_url, # "Accept-language": "ZH-CN", # "Origin": "Https://api.weibo.com", # "accept-encoding": "gzip, deflate", # "User-agent": "mozilla/5.0 (Windows NT 6.1; WOW64; trident/7.0; EIE10; Zhcnmse;
                   rv:11.0) Like Gecko ", #" Host ":" login.sina.com.cn ", #" Connection ":" Keep-alive ", # "Cache-control": "No-cache",} URL = "https://login.sina.com.cn/sso/login.php?" Client=ssologin.js (v1.4.15) "req = Urllib2. Request (URL, fields, headers) F = urllib2.urlopen (req) data = Json.loads (F.read ()) return data["Ti Cket "] def get_code_security (self): ticket = Self.get_ticket () fields = Urllib.urleNcode ({' Action ': ' Submit ', # must ' Display ': ' Default ', ' Withofficalflag ': ' 0 ', # must ' Quick_auth ': ' null ', ' withofficalaccount ': ', ' scope ': ', ' Ticket ': Ticke T, # must ' Isloginsina ': ', ' response_type ': ' Code ', # must ' Regcallback ': ' Https://api . weibo.com/2/oauth2/authorize?client_id= ' +self. app_key+ ' &response_type=code&display=default&redirect_uri= ' +self. redirect_url+ ' &from=&with_cookie= ', ' Redirect_uri ': self. Redirect_url, # must be ' client_id ': self.
            App_key, # must ' appkey62 ': ' kxr5r ', ' state ': ', # must ' Verifytoken ': ' null ',
        ' From ': ', # must ' userId ': ', # This method does not need to fill in the plaintext id ' passwd ': ', # This method does not need to fill in plaintext password} Login_url = ' https://api.weibo.com/oauth2/authorize ' headers = {"User-agent": "mozilla/5.0" (Windows NT 6.1; WOW64; trident/7.0; EIE10; Zhcnmse; rv:11.0) Like Gecko "," Referer ": Self. Callback_url, "Content-type": "Application/x-www-form-urlencoded",} req = u Rllib2.
        Request (Login_url, fields, headers) req_ =urllib2.urlopen (req) Return_redirect_uri = Req_.geturl () Code = Re.findall (? <=code%3d). { 32}| (? <=code=).
        {} ", Return_redirect_uri) # URL = with%3d or = Direct representation of print Code return code def Get_code_ns (self): Fields = Urllib.urlencode ({' Action ': ' Submit ', # must ' Display ': ' Default ', ' WI 
            Thofficalflag ': ' 0 ', # must be ' Quick_auth ': ' null ', ' withofficalaccount ': ', ' scope ': ', ' Ticket ': ', # must ' Isloginsina ': ', ' response_type ': ' Code ', # must ' re Gcallback ': ', ' Redirect_uri ': self. Redirect_url, # must be ' client_id ': self. App_key, # must be ' Appkey62 ': ' kxr5r ', ' state ': ', # must ' Verifytoken ': ' null ', ' from ': ', # must ' us Erid ': Self. USER_ID, # must be ' passwd ': self. USER_PSWD, # must}) Login_url = ' https://api.weibo.com/oauth2/authorize ' headers = {' User-agen T ":" mozilla/5.0 (Windows NT 6.1; WOW64; trident/7.0; EIE10; Zhcnmse; rv:11.0) Like Gecko "," Referer ": Self. Callback_url, "Content-type": "Application/x-www-form-urlencoded",} r = URL Lib2. Request (Login_url, fields, headers) opener = Get_opener (False) Urllib2.install_opener (opener) try : F = Opener.open (r) Return_redirect_uri = f.url print "NS1", Return_redirect_u RI except Urllib2. Httperror, E:return_redirect_uri = E.geturl () print "NS2", Return_redirect_uri # Fetch to The code #code returned = Return_redirect_uri. Split (' = ') [1] # The following I use a regular rewrite, so that the code cannot be extracted because of the URL change code = Re.findall (R) (? <=code%3d). 32}| (? <=code=).
    {} ", Return_redirect_uri) # URL = =%3d or = Direct representation of print code return code if __name__ =" __main__ ": App_key = U ' # app KEY app_secret = U ' # app SECRET redirect_url = ' Http://apps.weibo.com/zhanhisnshows ' cl ient = Apiclient (App_key=app_key, App_secret=app_secret, redirect_uri=redirect_url) Callback_url = Client.get_authori Ze_url () print Callback_url API = Sinaapi (Callback_url, App_key, Redirect_url, username, password) code = A Pi.get_code_security () #code = Api.get_code_ns () http://"" "" "#webbrowser. Open_new (URL) #获取code = later content cod  
    E = Raw_input (' Enter the content behind the code in the URL press ENTER: ') print code, "code" "" "Requests = Client.request_access_token (code) Access_token = requests.access_token # Sina returns token, similar to abc123xyz456 expires_in = requests.expires_in # set to get Access_token Client.sEt_access_token (Access_token, expires_in) print client.statuses__public_timeline () statuses = Client.statuses_  _public_timeline () [' statuses '] length = len (statuses) #输出了部分信息 for I in Range (0,length): Print U ' nickname: ' +statuses[i][' user '] [' screen_name '] print u ' profile: ' +statuses[i][' user '] [' description '] print u ' position:   ' +statuses[i][' user '] [' Location '] print U ' Weibo: ' +statuses[i][' text ']

3. Detailed data access details please see API:HTTP://OPEN.WEIBO.COM/WIKI/%E5%BE%AE%E5%8D%9AAPI. Mr. Liaoche about the API: Click on the open link to see. You'll know how to customize the command after reading the top two articles. Very good tutorial. Mr. Liao really did a lot of things. Thank. Last edited on: 2014.05.24 9:54

File free download address: weibo.py &weiboapi.py

This article is original by @the_third_wave. Do not update regularly, please correct me if there are any errors.

Sina Weibo attention: @The_third_wave

If this blog is helpful to you, for good network environment, do not recommend reprint, recommend collection. If you must reprint, please bring the suffix and this address.

Related Article

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.