03 Getting started with Python programming API: (2) Using Sina Weibo API in Python3

Review the API usage process

In the previous article, Python programming API entry: (1) Using Baidu Map API to check geographic coordinates , through the use of Baidu Map API, we see that the general process of API call is: generate url in the format specified by the API -> through urllib Read the data in the url -> parse the data in json format. Next, let's start to study the use of Sina Weibo API!

Ready to work

Sina Weibo Open Platform is a platform for using Sina Weibo API.
Sina Weibo API
After logging in to the platform with a Weibo account, apply to become a developer, and you will get a unique App Key and App Secret after creating a new application. (Note: The application does not need to be submitted for review, as long as a new application system is created, the Key and Secret will be assigned.) These two information can also be found in "My Application/Application Information/Basic Information". There is also an item of "My Application/Application Information/Advanced Information" on this page. Click to enter and set the relevant information of the OAuth2.0 authorization callback page. If you don’t know what to fill in, you can set it as the default callback page: https: //api.weibo.com/oauth2/default.html. These three pieces of information are needed later, please copy and save to the file.

New Features of Weibo API

Compared with Baidu Map API, Sina Weibo API adds OAuth2.0 protocol for user authentication and authorization. Here is only a brief description (for interested students, please refer to the online document diagram): Through this agreement, third-party applications can obtain user authorization, and then use the license to obtain a token from the authorization server for subsequent queries from the API server Verify identity when data.
oAuth2
This verification link increases the complexity of url generation. Fortunately, there is already an SDK toolkit provided by Mr. Xuefeng Liao on the website: sinaweibopy (Mr. Liao’s github address seems to have changed its name, so many old links on the Internet are invalid. This is a new valid link. ), but this program is written based on the Python2 environment. Some system libraries of Python3 have changed, and errors are often reported when the program is called. As a Python beginner, it is undoubtedly difficult to adapt the program to the Python3 environment. Fortunately, a great god did this work. Thank you owolf for the SDK rewritten for Python3: sinaweibopy3 . I have used it and it runs normally. You can download it. I also recommend owolf's article the most detailed in the entire network: python3 calls the Sina Weibo API interface to get data .

Simple example

Let me introduce the process of using Sina Weibo API to provide reference for new students.

1. Parameter setting
import sinaweibopy3
import webbrowser
import json
APP_KEY =' 填入你的App Key'  
APP_SECRET=' 填入你的App Secret'
REDIRECT_URL =' 填入你的授权回调页'

Note:

  • This file needs to be placed in the same folder as sinaweibopy3.py.
  • The three pieces of information filled in are all the information mentioned in the preparation .

Let’s talk about a bug caused by my carelessness here, and give you a reminder. When I started running the program, the error message "redirect address does not match" appeared every time:

Error logging in with Weibo account! An error occurred while authorizing a third-party application. Please contact the developer of the third-party application: XXX or try again later.
Error code: 21322 Redirection address does not match

To find a solution on the Internet, you need to set up a callback page, but I have already set it in the previous steps. Why do I still have this problem? Later, I saw an article mentioning that the callback page address should be consistent with the REDIRECT_URL in the program. I thought of the program example as http://api.weibo.com/oauth2/default.html, which is the http:beginning, and I’m filling in When I saw that the address was the same, there was no change, but the website was the https:beginning, and 's'the difference was one address. I didn't expect it to be a big difference!

2.OAuth2.0 verification generated url
client = sinaweibopy3.APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=REDIRECT_URL)
url = client.get_authorize_url()
webbrowser.open_new(url)
result = client.request_access_token(input("please input code: "))
client.set_access_token(result.access_token, result.expires_in)

Note: This is the process of calling sinaweibopy3 to implement user authorization in OAuth2.0 -> getting Token. When the program runs client.request_access_token, an input prompt "please input code:" will pop up, asking for code? What does it mean? Open the browser and you will see the OAuth2.0 verification callback page. 'code='There is a string of characters after the address bar . This is the Token information we want. Copy it and paste it in, and the program continues to run.

3. Read data from API

Run the following code to read public Weibo data and display the results.

result=client.public_timeline()
print(json.dumps(result,indent=2,ensure_ascii=False))

By looking at the data structure, specific information can be extracted. For example, the following code can be used to output the user's Weibo nickname, location and the latest Weibo text.

number=result["total_number"]
print(number,"users:")
for u in result["statuses"]:
    print(u["user"]["screen_name"])
    print(u["user"]["location"])
    print(u["text"])

Advanced

What if you want to query other information, such as getting a user's watch list? Let us try to write the corresponding function.

1. View function information

The specified URL in the Sina Weibo API: https://api.weibo.com/2/friendships/friends.json
url
and the defined request parameters are: access_token, uid, screen_name, count, cursor, time_status.
parametersAmong them, access_token needs to be filled in, uid and screen_name are user id and nickname respectively. Both must be filled in and only one is required. (Note: After the interface is upgraded, it can only be the current authorized user) The default parameters can be used for count and cursor. Count is the number of records returned on a single page, the default is 5, and the maximum is not more than 5. The cursor returns the result of the cursor. trim_status is a switch to display the status field, 0: return the complete status field, 1: return only the status_id, the default is 1.

2. Write a fs_friends()function

First check, how is it implemented in sinaweibopy3.py public_timeline()?

def public_timeline(self):       
        result = _http_get('%s'% (self.api_url)  + 'statuses/public_timeline.json',
                           access_token=self.access_token, 
                           count=50, 
                           page=1, 
                           base_app=0,
                )
        return result

Control codes found %s'% (self.api_url)that https://api.weibo.com/2, so we just need to 'statuses/public_timeline.json'change 'friendships/friends.json', and add the required request parameters, you can write a needed fs_friends()function:

def fs_friends(self):
        result=_http_get('%s'% (self.api_url)  + 'friendships/friends.json', 
                           access_token=self.access_token, 
                           screen_name='填入你自己的微博昵称' ,
                           trim_status=0,
        )
        return result

Note: trim_status defaults to 1, and it is set to 0 to get the complete status field (including the latest Weibo text).

3. Call the fs_friends()function in the main program

Refer to the original client.public_timeline()and get the following code:

result = client.fs_friends()
print(json.dumps(result,indent=2,ensure_ascii=False))

In this way, you can see the list of people you are following, including basic information and the latest Weibo.

Furthermore, the latest Weibo content can be extracted through the following code:

for u in result['users']:
    print("\n",u['screen_name'])
    print(u['location'])
    if('status' not in u):
        print('not found\n')
        continue
    print(u['status']['text'])

Thinking

The following are the questions I am still thinking about. Welcome to exchange suggestions, thank you!
1. The count in the request parameter setting is not greater than 5. When I actually run the program, I only see 4 following users and the Weibo text. Can I read more users? How to read?
2. I also tried to write the query function status/home_timeline (get the latest Weibo of the currently logged-in user and the user he is following (authorized)), but because of parameter settings, the display result is Null (empty). I think the problem lies in the max_id parameter. The description points out: If this parameter is specified, the microblog with ID less than or equal to max_id will be returned. The default is 0, but how big is it reasonable? I am a little confused.

Guess you like

Origin blog.csdn.net/applebear1123/article/details/103490564