Crawling with Python and Twitter API 2-Implementation of user search function

What to do this time

Until the last time, we implemented the Butler class for simple search of tweets and the Tweet class for handling tweets. This time, I would like to implement the function to search for User and the User class in the Butler class.

Implementation up to the last time

I will put the code up to the last time first.

tweet_butler.py


from . import config
from requests_oauthlib import OAuth1Session
import json

class Butler:
    def __init__(self,setting = config):
        self.api = OAuth1Session(setting.Consumer_Key, setting.Consumer_Secret_Key, setting.Access_Token, setting.Access_Secret_Token)
        self.search_url = "https://api.twitter.com/1.1/search/tweets.json"

    def search(self,word,count=10):
        params = {"q":word,"count":count}
        res = self.api.get(self.search_url, params = params)
        if res.status_code == 200:
            search_results = json.loads(res.text)
        tweets = [Tweet(result) for result in search_results["statuses"]]
        return tweets

class Tweet:
    def __init__(self,tweet):
        self.dict = tweet
        self.tweet_id = tweet["id"]
        self.user_id = tweet["user"]["id"]
        self.user_name = tweet["user"]["screen_name"]
        self.text = tweet["text"]
        self.created_at = tweet["created_at"]
        self.favorite_count = tweet["favorite_count"]
        self.hashtags = tweet["entities"]["hashtags"]
        self.symbols = tweet["entities"]["symbols"]
        self.mention = tweet["entities"]["user_mentions"]

    def get_text(self):
        return self.text

User search method

You can search the API simply by sending a GET request to a URL. There seem to be the following three methods when searching for users. ・ Users / lookup ・ Users / search ・ Users / show search is to search for users who hit a certain word, show is to output only one user with the same id and screen_name, lookup is extended to multiple people in show, and it is listed in id and screen_name. Can be entered. None of them are difficult to implement, but this time we will use show first.

Implementation of user search function

The first thing you need is an API token. This was explained last time, so I will omit it. Crawling with Python and Twitter API 1-Simple search function

Next is the resource URL for users / show.  https://api.twitter.com/1.1/users/show.json You also need to know about the json files you throw into this API to implement.


{
  "Name": "name",
  "user_id": "id",
  "screen_name": "screen_name",
  "include_entities": "include_entities",
}

The above four are the elements that can be used as the input of the json file. Of these, one of Name, user_id, screen_name is always required.

The rest is implementation. This is not much different from the last time. Implement as a method of the Butler class. Butler.get_user_by_id() First, it is a method to get the user from the ID using showAPI.

tweet_butler.py


class Butler:
    def __init__(self, setting = config):
        self.get_user_url = "https://api.twitter.com/1.1/users/show.json"
              :
              :

    def get_user_by_id(self, id):
        params = {"user_id":user_id}
        res = self.api.get(self.get_user_url, params = params)
        if res.status_code == 200:
            search_results = json.loads(res.text)
        else:
            assert False, "{} error happen in get_user_by_id method".format(res.status_code)
        return User(search_results)

Butler.get_user_by_name Next is the method to get the user from screen_name. The API used is the same

tweet_butler.py


        :
        :
def get_user_by_name(self,name):
        params = "Name":name}
        res = self.api.get(self.get_user_url, params =params)
        if res.status_code == 200:
            search_results = json.loads(res.text)
        else:
            assert False, "{} error happen in get_user_by_name method".format(res.status_code)
        return User(search_results)

Implementation of User class

This time, I won't put a big deal on the User class.

tweet_butler.py



class User:
    def __init__(self, user_dict):
        self.dict = user_dict
        self.id = user_dict["id"]
        self.name = user_dict["name"]
        self.screen_name = user_dict["screen_name"]

I'm sorry for the omission.

Tweet class improvements

It seems that the user object is included in the Tweet object returned in the response, so add a new get_user method as a method of the Tweet class. I've also changed some of the class variable names.

tweet_butler.py


class Tweet:
    def __init__(self,tweet):
        self.dict = tweet
        self.id = tweet["id"]
        self.user_id = tweet["user"]["id"]
        self.user_name = tweet["user"]["screen_name"]
        self.text = tweet["text"]
        self.created_at = tweet["created_at"]
        self.favorite_count = tweet["favorite_count"]
        self.hashtags = tweet["entities"]["hashtags"]
        self.symbols = tweet["entities"]["symbols"]
        self.mention = tweet["entities"]["user_mentions"]
    
    def get_text(self):
        return self.text
    
##########The part below is newly added###########
    def get_user(self):
        return User(self.dict["user"])


Continue

Next, I would like to enable user search to be searched using the users / search API and to be able to retrieve tweets of a specific user.

reference

Get tweets from specific users on Twitter twitter developer

Recommended Posts

Crawling with Python and Twitter API 2-Implementation of user search function
Crawling with Python and Twitter API 1-Simple search function
Implementation of TRIE tree with Python and LOUDS
Use Twitter API with Python
Search twitter tweets with python
[Python] Get user information and article information with Qiita API
Build API server for checking the operation of front implementation with python3 and Flask
Try hitting the Twitter API quickly and easily with Python
I tried follow management with Twitter API and Python (easy)
Introduction and implementation of activation function
Implementation of Dijkstra's algorithm with python
Coexistence of Python2 and 3 with CircleCI (1.0)
Implementation of CRUD using REST API with Python + Django Rest framework + igGrid
Collecting information from Twitter with Python (Twitter API)
Get the number of articles accessed and likes with Qiita API + Python
[Unity (C #), Python] API communication study memo ③ Implementation of simplified login function
Automatically search and download YouTube videos with Python
Causal reasoning and causal search with Python (for beginners)
I tried function synthesis and curry with python
Get Gmail subject and body with Python and Gmail API
Continuation of multi-platform development with Electron and Python
Explanation of edit distance and implementation in Python
Example of reading and writing CSV with Python
Deep Learning from scratch The theory and implementation of deep learning learned with Python Chapter 3
Sequential search with Python
Automate UI testing with Selenium API | Crawling websites with python
Get a large amount of Starbucks Twitter data with python and try data analysis Part 1
[Python of Hikari-] Chapter 06-02 Function (argument and return value 1)
Perform a Twitter search from Python and try to generate sentences with Markov chains.
Easy partial download of mp4 with python and youtube-dl!
[# 2] Make Minecraft with Python. ~ Model drawing and player implementation ~
Visualize the range of interpolation and extrapolation with python
Automatic follow on Twitter with python and selenium! (RPA)
Second half of the first day of studying Python Try hitting the Twitter API with Bottle
Binary search with python
Binary search with Python3
Search Twitter using Python
Search and save images of Chino Kafu from Twitter
Overview of generalized linear models and implementation in Python
Comparison of CoffeeScript with JavaScript, Python and Ruby grammar
Version control of Node, Ruby and Python with anyenv
[Python Seaborn Graph Library] About User Warning of axes.color_cycle is deprecated and replaced with axes.prop_cycle
Easy to use Nifty Cloud API with botocore and python
Python implementation of CSS3 blend mode and talk of color space
Perform isocurrent analysis of open channels with Python and matplotlib
Solving with Ruby and Python AtCoder ABC151 D Breadth-first search
Associate Python Enum with a function and make it Callable
Check the scope of local variables with the Python locals function.
Let's touch the API of Netatmo Weather Station with Python. #Python #Netatmo
Get rid of dirty data with Python and regular expressions
Detect objects of a specific color and size with Python
Streamline information gathering with the Twitter API and Slack bots
Web crawling, web scraping, character acquisition and image saving with python
[With simple explanation] Scratch implementation of deep Boltzmann machine with Python ②
[With simple explanation] Scratch implementation of deep Boltzmann machine with Python ①
Beginners of Google Maps API and Twitter API made "tweet map"
Collecting information from Twitter with Python (MySQL and Python work together)
Sample of HTTP GET and JSON parsing with python of pepper
Play with the password mechanism of GitHub Webhook and Python
Aggregate and analyze product prices using Rakuten Product Search API [Python]
Programming with Python and Tkinter