[Python] Get the number of views of all posted articles

Introduction

Get in order of likes Since I wrote the article, this time it is in order of the number of views.

Operating environment

What to do before writing code

Get a personal access token for Qiita.

  1. Access https://qiita.com/settings/applications (assuming you have logged in to Qiita)
  2. Press `` Issue a new token'' at the bottom of the screen. image.png
  3. Enter the intended use in Access Token Description, select read_qiita for Scope, and press Issue. image.png
  4. An alphanumeric character string will be displayed, so copy it. ( ** Personal information, so handle with care! ** </ font>)

code

Replace XXXXXXXXXXXXXXXXXXX with the issued access token.

import http.client
import requests
import json
import math

CONN = http.client.HTTPSConnection('qiita.com', 443)
USER_ID = 'riekure'
PER_PAGE = 20
URL = 'https://qiita.com/api/v2/authenticated_user/items'
HEADERS = {"content-type": "application/json", "Authorization": "Bearer XXXXXXXXXXXXXXXXXXX"}

class Api:
    #Return request result in JSON format
    @staticmethod
    def request(http, url) :
        CONN.request(http, url)
        res = CONN.getresponse()
        data = res.read().decode('utf-8')
        return json.loads(data)

    #Calculate the page number from the number of posts
    @staticmethod
    def page_count(items_count) :
        return math.floor(items_count / PER_PAGE) + 1

#Get the number of posts
items_count = Api.request('GET', '/api/v2/users/' + USER_ID)['items_count']
page = Api.page_count(items_count)

#Get all posted articles
all_article = {}
for i in range(page) :
    res = requests.get(URL + '?page=' + str(i+1), headers=HEADERS)
    list = res.json()
    for item in list :
        item_id = item['id']
        title = item['title']
        url = 'https://qiita.com/api/v2/items/' + item_id
        res = requests.get(url, headers=HEADERS)
        json = res.json()
        page_views_count = json['page_views_count']
        all_article.setdefault(title, page_views_count)

#Sort by descending number of views
# items()Becomes a tuple because it uses
tuple_items = sorted(all_article.items(), key=lambda x:x[1], reverse=True)
print(all_article)

#Display in markdown tabular format
print('|Article title|Number of views|')
print('|------------|--------------|')
for title, count in tuple_items:
    print('| ' + title + ' | ' + str(count) + ' |')

Execution result

As of June 28, 2020

Article title Number of views
Java 8 LocalDateTime type conversion(String, java.util.Date) 57161
[Oracle] How to get table column information by SQL 31390
How to convert a file to a byte array in Java 27834
Basic usage of git revert 25794
[Windows 10]The engineer who stretches his finger to the arrow keys is Zako! Was ridiculed (introduction of Change Key and AutoHotkey) 24472
Use inequality comparison operators in MyBatis SQL 22104
Steps to get Visual Studio Code available in Unity 21498
How to execute a command as a user who cannot log in + bonus 15843
[Java] Delete the specified number of characters from the end of StringBuilder 15558
Identifies and forcibly terminates the session during DB connection with Oracle SQL(KILL) 15035
【Java】 (list == null list.size() == 0)I don't like the fact that I'm checking NULL / empty 14769
[Java]What should I use to write a file? 12379
What is the difference between SimpleDateFormat and DateTimeFormatter? ?? 11016
[Unity] What to do when Standard Assets is not displayed in the Import Package 10817
I tried to implement a check process that makes errors other than alphanumeric symbols, hiragana, katakana, JIS 1st / 2nd level kanji in Java 10685
A confused story about a ternary operator with multiple conditional expressions 10414
AWS Certified Solutions Architect Associate(SAA)Failure experience 10263
AWS Certified Solutions Architect after 10 months of study-Associate-I can't pass, so I look back on how to study 9579
[Beginner]If you think that you are using AWS in the range of several hundred yen a month, you were charged about 2000 yen 8374
[MyBatis]Use Cursor when mapping large amounts of data 8049
A Java programmer studied Python.(About the type) 6873
How to set Windows 10 notebook PC built-in keyboard to JIS layout, Bluetooth connection keyboard to US layout 6566
How to find a process using a specific port number 6412
(Java 7 or later only)Objects are Objects.I want you to compare with equals 5907
Oracle SQL(11g)I want to reproduce the MySQL LIMIT OFFSET clause in 5880
[Unity]"Can't add script behavior XXXX.The script needs to derive from MonoBehaviour"4 ways to improve 5810
【Unity】Unity-Chan!Investigation results and solutions when a CS0234 error occurs in (Unity-chan) 5159
Unity +C in Visual Studio Community#Debug and run 5154
Mysql on Amazon Linux 2-What to do if the server cannot be installed 4797
Bottom 10%As a result of solving puzzles that can only be solved by bad engineers, the bottom 10%Turned out to be a bad engineer 4416
AWS Certified Solutions Architect over a year-Associate-I passed the exam, so I look back on my study method 4357
【Unity】UnityEditor.BuildPlayerWindow+What to do if you cannot build Android due to BuildMethodException 4098
[VS Code] Set the indent width, tab or space to use for each language 3509
Shortcut comparison for those migrating from Eclipse to IntelliJ IDEA(Windows) 3459
[Unity] When there is no response at startup in Windows 10 3445
【Unity】Application.LoadLevel was deprecated 3335
Aurora(MySQL)I got an error when I tried CREATE VIEW 3214
A Java programmer studied Python.(function(Method)about) 3046
Don't stop updating until you pass the AWS Certified Solutions Architect Associate! 2927
THETA Web API v2.How to run 1 with the curl command 2844
ESLint introduction story to eradicate fucking code mass production projects 2808
Be careful because the Oculus Rift can't be run on the Surface Book 2! 2706
[Unity] Summary of personally stuck things before building a project for Oculus Go 2680
[Unity] Component activation/Switch invalidation by pressing a button 2481
AWS Certified Solutions Architect to Address Table-Associate(SAA)* Updated from time to time 2467
A Java programmer studied Python.(for, if,while statement) 2360
.bash_Wrong profile settings, any command"command not found"Solution when it becomes 2242
[Unity] open when git add("Temp/UnityLockfile"):Causes of Permission denied and remedies 2018
How to prevent certain files from being deleted with the rm command etc.(chattr, lsattr command) 1815
Bottom 20%Solved a puzzle that only a bad engineer couldn't solve 1467
[Java]Java the functions I created in the past.io.File to NIO.Rewrite in 2 1398
【Git】fatal: protocol error: bad line length character:How to eliminate usag 1389
What to do if you can't connect to AWS Cloud9 in Chrome 1362
[Unity] Separate processing by distinguishing between Unity Editor and actual smartphone 1350
[Java 8]Alphabetical order and character string length sorting method that can be used in coding tests 1349
[Java 8]Until you convert standard input that can be used in coding tests into a list or array 1348
A Java programmer studied Python.(About decorators) 1325
[Python]Get a list of posts using the Qiita API+Looking back on 2018 1305
AWS Innovate Online Conference "Test Preparation Session 1: Designing a Recoverable Architecture" 1063
Most engineers couldn't solve Puzzle 3 1033
AWS Innovate Online Conference "Test Preparation Session 5: Defining an Architecture with Operational Excellence" 858
[Ruby] Can it be used in coding tests? How to receive values from standard input 801
AWS Innovate Online Conference "Test Preparation Session 4: Designing a Cost Optimization Architecture" 788
[Unity] Understanding asynchronous processing-Coroutine- 713
AWS Innovate Online Conference "Test Preparation Session 2: Defining a High Performance Architecture" 645
AWS Innovate Online Conference "Test Preparation Session 3: Defining Secure Applications and Architecture" 644
[Ruby] Array methods that Ruby beginners often use 564
[Unity] Understanding asynchronous processing ~ async/await edition ~ 463
[Ruby] I regret the reason why I made a mistake in the declaration of the 2D array and could not change the elements as expected. 448
[Unity] What to do if you get an "incomplete or corrupted download file" when installing Unity from Unity Hub 421
[Katalon Studio] How to change the default browser 395
[Katalon Studio] How to make a dark theme (black background) 390
The Like (LGTM) order has disappeared from My Page, so use the Qiita API to get it. 286
[Slack] Procedures for skipping messages using the Slack API 158
Scrum Development Glossary for those who don't have the time 98

Please note that it seems to include limited shared articles.

At the end

I want to graduate from Qiita, but I can't find a migration destination.

Recommended Posts

[Python] Get the number of views of all posted articles
Get the number of views of Qiita
Get the number of PVs of Qiita articles you posted with API
Get the number of digits
Get the number of articles accessed and likes with Qiita API + Python
How to get the number of digits in Python
Get the size (number of elements) of UnionFind in Python
Get the number of Youtube subscribers
Get the number of specific elements in a python list
[Python] Get the character code of the file
Get the number of readers of a treatise on Mendeley in Python
How to output the number of VIEWs, likes, and stocks of articles posted on Qiita to CSV (created with "Python + Qiita API v2")
Get the number of searches with a regular expression. SeleniumBasic VBA Python
Get the contents of git diff from python
Output the number of CPU cores in Python
[Python] Get / edit the scale label of the figure
[Python] Get the main topics of Yahoo News
Get the caller of a function in Python
Calculate the total number of combinations with python
[Python] Get the last updated date of the website
[Python] Get the day of the week (English & Japanese)
Get the update date of the Python memo file.
the zen of Python
python beginners tried to predict the number of criminals
[Python] A program that counts the number of valleys
[Python] Get the official file path of the shortcut file (.lnk)
[Python] Get the text of the law from the e-GOV Law API
[python] Get the list of classes defined in the module
Get the return code of the Python script from bat
[Python] Get the list of ExifTags names of Pillow library
[Python] Outputs all combinations of elements in the list
Get the operation status of JR West with Python
Get the URL of the HTTP redirect destination in Python
What happens if you graph the number of views and ratings/comments of the video of "Flag-chan!" [Python] [Graph]
10. Counting the number of lines
Towards the retirement of Python2
About the ease of Python
[Python] Get the previous month
Calculate the number of changes
About the features of Python
The Power of Pandas: Python
Python --Find out number of groups in the regex expression
[Homology] Count the number of holes in data with Python
Get the number of occurrences for each element in the list
Get all IP addresses of instances in the autoscaling group
Get the index of each element of the confusion matrix in Python
Get the source of the page to load infinitely with python.
I tried to get the number of days of the month holidays (Saturdays, Sundays, and holidays) with python
The story of Python and the story of NaN
Count the number of Thai and Arabic characters well in Python
[Python] The stumbling block of import
Note: Get the first and last items of Python OrderedDict non-destructively
[Python] Let's reduce the number of elements in the result in set operations
Get the desktop path in Python
Existence from the viewpoint of Python
[Python] How to get the first and last days of the month
Get the weather with Python requests
Calculation of the number of Klamer correlations
Get the weather with Python requests 2
Get the script path in Python
How to get the Python version