1621467780
This article is all about configuring and installing freestyle project using Jenkins. This guide will also provide instructions to set up Jenkins and Java as well.
Jenkins is one of the most popular tools for continuous integration and continuous Delivery on any platform and It’s a self-contained, open-source automation tool written in java. It also provides hundreds of plugins to support building, deploying and automating any project and also supports version control tools like Subversion , Git, Mercurial, and Maven and allows for faster delivery of Software by working with a large number of deployment and testing technologies.
A Jenkins project is a repeatable build job which contains step and post-build actions. The types of actions you can perform in a build step or post-build action are quite limited. There are many standard plugins available within a Jenkins freestyle project to help you overcome this problem. In the other words , They allow you to configure build triggers and offer project-based security for your Jenkins project.
#jenkins #java
1593867420
Android Projects with Source Code – Your entry pass into the world of Android
Hello Everyone, welcome to this article, which is going to be really important to all those who’re in dilemma for their projects and the project submissions. This article is also going to help you if you’re an enthusiast looking forward to explore and enhance your Android skills. The reason is that we’re here to provide you the best ideas of Android Project with source code that you can choose as per your choice.
These project ideas are simple suggestions to help you deal with the difficulty of choosing the correct projects. In this article, we’ll see the project ideas from beginners level and later we’ll move on to intermediate to advance.
Before working on real-time projects, it is recommended to create a sample hello world project in android studio and get a flavor of project creation as well as execution: Create your first android project
Android Project: A calculator will be an easy application if you have just learned Android and coding for Java. This Application will simply take the input values and the operation to be performed from the users. After taking the input it’ll return the results to them on the screen. This is a really easy application and doesn’t need use of any particular package.
To make a calculator you’d need Android IDE, Kotlin/Java for coding, and for layout of your application, you’d need XML or JSON. For this, coding would be the same as that in any language, but in the form of an application. Not to forget creating a calculator initially will increase your logical thinking.
Once the user installs the calculator, they’re ready to use it even without the internet. They’ll enter the values, and the application will show them the value after performing the given operations on the entered operands.
Source Code: Simple Calculator Project
Android Project: This is a good project for beginners. A Reminder App can help you set reminders for different events that you have throughout the day. It’ll help you stay updated with all your tasks for the day. It can be useful for all those who are not so good at organizing their plans and forget easily. This would be a simple application just whose task would be just to remind you of something at a particular time.
To make a Reminder App you need to code in Kotlin/Java and design the layout using XML or JSON. For the functionality of the app, you’d need to make use of AlarmManager Class and Notifications in Android.
In this, the user would be able to set reminders and time in the application. Users can schedule reminders that would remind them to drink water again and again throughout the day. Or to remind them of their medications.
Android Project: Another beginner’s level project Idea can be a Quiz Application in android. Here you can provide the users with Quiz on various general knowledge topics. These practices will ensure that you’re able to set the layouts properly and slowly increase your pace of learning the Android application development. In this you’ll learn to use various Layout components at the same time understanding them better.
To make a quiz application you’ll need to code in Java and set layouts using xml or java whichever you prefer. You can also use JSON for the layouts whichever preferable.
In the app, questions would be asked and answers would be shown as multiple choices. The user selects the answer and gets shown on the screen if the answers are correct. In the end the final marks would be shown to the users.
Android Project: Tic-Tac-Toe is a nice game, I guess most of you all are well aware of it. This will be a game for two players. In this android game, users would be putting X and O in the given 9 parts of a box one by one. The first player to arrange X or O in an adjacent line of three wins.
To build this game, you’d need Java and XML for Android Studio. And simply apply the logic on that. This game will have a set of three matches. So, it’ll also have a scoreboard. This scoreboard will show the final result at the end of one complete set.
Upon entering the game they’ll enter their names. And that’s when the game begins. They’ll touch one of the empty boxes present there and get their turn one by one. At the end of the game, there would be a winner declared.
Source Code: Tic Tac Toe Game Project
Android Project: A stopwatch is another simple android project idea that will work the same as a normal handheld timepiece that measures the time elapsed between its activation and deactivation. This application will have three buttons that are: start, stop, and hold.
This application would need to use Java and XML. For this application, we need to set the timer properly as it is initially set to milliseconds, and that should be converted to minutes and then hours properly. The users can use this application and all they’d need to do is, start the stopwatch and then stop it when they are done. They can also pause the timer and continue it again when they like.
Android Project: This is another very simple project idea for you as a beginner. This application as the name suggests will be a To-Do list holding app. It’ll store the users schedules and their upcoming meetings or events. In this application, users will be enabled to write their important notes as well. To make it safe, provide a login page before the user can access it.
So, this app will have a login page, sign-up page, logout system, and the area to write their tasks, events, or important notes. You can build it in android studio using Java and XML at ease. Using XML you can build the user interface as user-friendly as you can. And to store the users’ data, you can use SQLite enabling the users to even delete the data permanently.
Now for users, they will sign up and get access to the write section. Here the users can note down the things and store them permanently. Users can also alter the data or delete them. Finally, they can logout and also, login again and again whenever they like.
Android Project: This app is aimed at the conversion of Roman numbers to their significant decimal number. It’ll help to check the meaning of the roman numbers. Moreover, it will be easy to develop and will help you get your hands on coding and Android.
You need to use Android Studio, Java for coding and XML for interface. The application will take input from the users and convert them to decimal. Once it converts the Roman no. into decimal, it will show the results on the screen.
The users are supposed to just enter the Roman Number and they’ll get the decimal values on the screen. This can be a good android project for final year students.
Android Project: Well, coming to this part that is Virtual Dice or a random no. generator. It is another simple but interesting app for computer science students. The only task that it would need to do would be to generate a number randomly. This can help people who’re often confused between two or more things.
Using a simple random number generator you can actually create something as good as this. All you’d need to do is get you hands-on OnClick listeners. And a good layout would be cherry on the cake.
The user’s task would be to set the range of the numbers and then click on the roll button. And the app will show them a randomly generated number. Isn’t it interesting ? Try soon!
Android Project: This application is very important for you as a beginner as it will let you use your logical thinking and improve your programming skills. This is a scientific calculator that will help the users to do various calculations at ease.
To make this application you’d need to use Android Studio. Here you’d need to use arithmetic logics for the calculations. The user would need to give input to the application that will be in terms of numbers. After that, the user will give the operator as an input. Then the Application will calculate and generate the result on the user screen.
Android Project: An SMS app is another easy but effective idea. It will let you send the SMS to various no. just in the same way as you use the default messaging application in your phone. This project will help you with better understanding of SMSManager in Android.
For this application, you would need to implement Java class SMSManager in Android. For the Layout you can use XML or JSON. Implementing SMSManager into the app is an easy task, so you would love this.
The user would be provided with the facility to text to whichever number they wish also, they’d be able to choose the numbers from the contact list. Another thing would be the Textbox, where they’ll enter their message. Once the message is entered they can happily click on the send button.
#android tutorials #android application final year project #android mini projects #android project for beginners #android project ideas #android project ideas for beginners #android projects #android projects for students #android projects with source code #android topics list #intermediate android projects #real-time android projects
1657764000
You can use the data you can get from social media in a number of ways, like sentiment analysis (analyzing people's thoughts) on a specific issue or field of interest.
There are several ways you can scrape (or gather) data from Twitter. And in this article, we will look at two of those ways: using Tweepy and Snscrape.
We will learn a method to scrape public conversations from people on a specific trending topic, as well as tweets from a particular user.
Now without further ado, let’s get started.
Now, before we get into the implementation of each platform, let's try to grasp the differences and limits of each platform.
Tweepy is a Python library for integrating with the Twitter API. Because Tweepy is connected with the Twitter API, you can perform complex queries in addition to scraping tweets. It enables you to take advantage of all of the Twitter API's capabilities.
But there are some drawbacks – like the fact that its standard API only allows you to collect tweets for up to a week (that is, Tweepy does not allow recovery of tweets beyond a week window, so historical data retrieval is not permitted).
Also, there are limits to how many tweets you can retrieve from a user's account. You can read more about Tweepy's functionalities here.
Snscrape is another approach for scraping information from Twitter that does not require the use of an API. Snscrape allows you to scrape basic information such as a user's profile, tweet content, source, and so on.
Snscrape is not limited to Twitter, but can also scrape content from other prominent social media networks like Facebook, Instagram, and others.
Its advantages are that there are no limits to the number of tweets you can retrieve or the window of tweets (that is, the date range of tweets). So Snscrape allows you to retrieve old data.
But the one disadvantage is that it lacks all the other functionalities of Tweepy – still, if you only want to scrape tweets, Snscrape would be enough.
Now that we've clarified the distinction between the two methods, let's go over their implementation one by one.
Before we begin using Tweepy, we must first make sure that our Twitter credentials are ready. With that, we can connect Tweepy to our API key and begin scraping.
If you do not have Twitter credentials, you can register for a Twitter developer account by going here. You will be asked some basic questions about how you intend to use the Twitter API. After that, you can begin the implementation.
The first step is to install the Tweepy library on your local machine, which you can do by typing:
pip install git+https://github.com/tweepy/tweepy.git
Now that we’ve installed the Tweepy library, let’s scrape 100 tweets from a user called john
on Twitter. We'll look at the full code implementation that will let us do this and discuss it in detail so we can grasp what’s going on:
import tweepy
consumer_key = "XXXX" #Your API/Consumer key
consumer_secret = "XXXX" #Your API/Consumer Secret Key
access_token = "XXXX" #Your Access token key
access_token_secret = "XXXX" #Your Access token Secret key
#Pass in our twitter API authentication key
auth = tweepy.OAuth1UserHandler(
consumer_key, consumer_secret,
access_token, access_token_secret
)
#Instantiate the tweepy API
api = tweepy.API(auth, wait_on_rate_limit=True)
username = "john"
no_of_tweets =100
try:
#The number of tweets we want to retrieved from the user
tweets = api.user_timeline(screen_name=username, count=no_of_tweets)
#Pulling Some attributes from the tweet
attributes_container = [[tweet.created_at, tweet.favorite_count,tweet.source, tweet.text] for tweet in tweets]
#Creation of column list to rename the columns in the dataframe
columns = ["Date Created", "Number of Likes", "Source of Tweet", "Tweet"]
#Creation of Dataframe
tweets_df = pd.DataFrame(attributes_container, columns=columns)
except BaseException as e:
print('Status Failed On,',str(e))
time.sleep(3)
Now let's go over each part of the code in the above block.
import tweepy
consumer_key = "XXXX" #Your API/Consumer key
consumer_secret = "XXXX" #Your API/Consumer Secret Key
access_token = "XXXX" #Your Access token key
access_token_secret = "XXXX" #Your Access token Secret key
#Pass in our twitter API authentication key
auth = tweepy.OAuth1UserHandler(
consumer_key, consumer_secret,
access_token, access_token_secret
)
#Instantiate the tweepy API
api = tweepy.API(auth, wait_on_rate_limit=True)
In the above code, we've imported the Tweepy library into our code, then we've created some variables where we store our Twitter credentials (The Tweepy authentication handler requires four of our Twitter credentials). So we then pass in those variable into the Tweepy authentication handler and save them into another variable.
Then the last statement of call is where we instantiated the Tweepy API and passed in the require parameters.
username = "john"
no_of_tweets =100
try:
#The number of tweets we want to retrieved from the user
tweets = api.user_timeline(screen_name=username, count=no_of_tweets)
#Pulling Some attributes from the tweet
attributes_container = [[tweet.created_at, tweet.favorite_count,tweet.source, tweet.text] for tweet in tweets]
#Creation of column list to rename the columns in the dataframe
columns = ["Date Created", "Number of Likes", "Source of Tweet", "Tweet"]
#Creation of Dataframe
tweets_df = pd.DataFrame(attributes_container, columns=columns)
except BaseException as e:
print('Status Failed On,',str(e))
In the above code, we created the name of the user (the @name in Twitter) we want to retrieved the tweets from and also the number of tweets. We then created an exception handler to help us catch errors in a more effective way.
After that, the api.user_timeline()
returns a collection of the most recent tweets posted by the user we picked in the screen_name
parameter and the number of tweets you want to retrieve.
In the next line of code, we passed in some attributes we want to retrieve from each tweet and saved them into a list. To see more attributes you can retrieve from a tweet, read this.
In the last chunk of code we created a dataframe and passed in the list we created along with the names of the column we created.
Note that the column names must be in the sequence of how you passed them into the attributes container (that is, how you passed those attributes in a list when you were retrieving the attributes from the tweet).
If you correctly followed the steps I described, you should have something like this:
Image by Author
Now that we are done, let's go over one more example before we move into the Snscrape implementation.
In this method, we will be retrieving a tweet based on a search. You can do that like this:
import tweepy
consumer_key = "XXXX" #Your API/Consumer key
consumer_secret = "XXXX" #Your API/Consumer Secret Key
access_token = "XXXX" #Your Access token key
access_token_secret = "XXXX" #Your Access token Secret key
#Pass in our twitter API authentication key
auth = tweepy.OAuth1UserHandler(
consumer_key, consumer_secret,
access_token, access_token_secret
)
#Instantiate the tweepy API
api = tweepy.API(auth, wait_on_rate_limit=True)
search_query = "sex for grades"
no_of_tweets =150
try:
#The number of tweets we want to retrieved from the search
tweets = api.search_tweets(q=search_query, count=no_of_tweets)
#Pulling Some attributes from the tweet
attributes_container = [[tweet.user.name, tweet.created_at, tweet.favorite_count, tweet.source, tweet.text] for tweet in tweets]
#Creation of column list to rename the columns in the dataframe
columns = ["User", "Date Created", "Number of Likes", "Source of Tweet", "Tweet"]
#Creation of Dataframe
tweets_df = pd.DataFrame(attributes_container, columns=columns)
except BaseException as e:
print('Status Failed On,',str(e))
The above code is similar to the previous code, except that we changed the API method from api.user_timeline()
to api.search_tweets()
. We've also added tweet.user.name
to the attributes container list.
In the code above, you can see that we passed in two attributes. This is because if we only pass in tweet.user
, it would only return a dictionary user object. So we must also pass in another attribute we want to retrieve from the user object, which is name
.
You can go here to see a list of additional attributes that you can retrieve from a user object. Now you should see something like this once you run it:
Image by Author.
Alright, that just about wraps up the Tweepy implementation. Just remember that there is a limit to the number of tweets you can retrieve, and you can not retrieve tweets more than 7 days old using Tweepy.
As I mentioned previously, Snscrape does not require Twitter credentials (API key) to access it. There is also no limit to the number of tweets you can fetch.
For this example, though, we'll just retrieve the same tweets as in the previous example, but using Snscrape instead.
To use Snscrape, we must first install its library on our PC. You can do that by typing:
pip3 install git+https://github.com/JustAnotherArchivist/snscrape.git
Snscrape includes two methods for getting tweets from Twitter: the command line interface (CLI) and a Python Wrapper. Just keep in mind that the Python Wrapper is currently undocumented – but we can still get by with trial and error.
In this example, we will use the Python Wrapper because it is more intuitive than the CLI method. But if you get stuck with some code, you can always turn to the GitHub community for assistance. The contributors will be happy to help you.
To retrieve tweets from a particular user, we can do the following:
import snscrape.modules.twitter as sntwitter
import pandas as pd
# Created a list to append all tweet attributes(data)
attributes_container = []
# Using TwitterSearchScraper to scrape data and append tweets to list
for i,tweet in enumerate(sntwitter.TwitterSearchScraper('from:john').get_items()):
if i>100:
break
attributes_container.append([tweet.date, tweet.likeCount, tweet.sourceLabel, tweet.content])
# Creating a dataframe from the tweets list above
tweets_df = pd.DataFrame(attributes_container, columns=["Date Created", "Number of Likes", "Source of Tweet", "Tweets"])
Let's go over some of the code that you might not understand at first glance:
for i,tweet in enumerate(sntwitter.TwitterSearchScraper('from:john').get_items()):
if i>100:
break
attributes_container.append([tweet.date, tweet.likeCount, tweet.sourceLabel, tweet.content])
# Creating a dataframe from the tweets list above
tweets_df = pd.DataFrame(attributes_container, columns=["Date Created", "Number of Likes", "Source of Tweet", "Tweets"])
In the above code, what the sntwitter.TwitterSearchScaper
does is return an object of tweets from the name of the user we passed into it (which is john).
As I mentioned earlier, Snscrape does not have limits on numbers of tweets so it will return however many tweets from that user. To help with this, we need to add the enumerate function which will iterate through the object and add a counter so we can access the most recent 100 tweets from the user.
You can see that the attributes syntax we get from each tweet looks like the one from Tweepy. These are the list of attributes that we can get from the Snscrape tweet which was curated by Martin Beck.
Credit: Martin Beck
More attributes might be added, as the Snscrape library is still in development. Like for instance in the above image, source
has been replaced with sourceLabel
. If you pass in only source
it will return an object.
If you run the above code, you should see something like this as well:
Image by Author
Now let's do the same for scraping by search.
import snscrape.modules.twitter as sntwitter
import pandas as pd
# Creating list to append tweet data to
attributes_container = []
# Using TwitterSearchScraper to scrape data and append tweets to list
for i,tweet in enumerate(sntwitter.TwitterSearchScraper('sex for grades since:2021-07-05 until:2022-07-06').get_items()):
if i>150:
break
attributes_container.append([tweet.user.username, tweet.date, tweet.likeCount, tweet.sourceLabel, tweet.content])
# Creating a dataframe to load the list
tweets_df = pd.DataFrame(attributes_container, columns=["User", "Date Created", "Number of Likes", "Source of Tweet", "Tweet"])
Again, you can access a lot of historical data using Snscrape (unlike Tweepy, as its standard API cannot exceed 7 days. The premium API is 30 days.). So we can pass in the date from which we want to start the search and the date we want it to end in the sntwitter.TwitterSearchScraper()
method.
What we've done in the preceding code is basically what we discussed before. The only thing to bear in mind is that until works similarly to the range function in Python (that is, it excludes the last integer). So if you want to get tweets from today, you need to include the day after today in the "until" parameter.
Image of Author.
Now you know how to scrape tweets with Snscrape, too!
Now that we've seen how each method works, you might be wondering when to use which.
Well, there is no universal rule for when to utilize each method. Everything comes down to a matter preference and your use case.
If you want to acquire an endless number of tweets, you should use Snscrape. But if you want to use extra features that Snscrape cannot provide (like geolocation, for example), then you should definitely use Tweepy. It is directly integrated with the Twitter API and provides complete functionality.
Even so, Snscrape is the most commonly used method for basic scraping.
Conclusion
In this article, we learned how to scrape data from Python using Tweepy and Snscrape. But this was only a brief overview of how each approach works. You can learn more by exploring the web for additional information.
I've included some useful resources that you can use if you need additional information. Thank you for reading.
Source: https://www.freecodecamp.org/news/python-web-scraping-tutorial/
1657773780
あなたがデータ愛好家であれば、実世界のデータの最も豊富な情報源の1つがソーシャルメディアであることに同意するでしょう。Twitterのようなサイトはデータでいっぱいです。
ソーシャルメディアから取得できるデータは、特定の問題や関心のある分野に関する感情分析(人々の考えを分析する)など、さまざまな方法で使用できます。
Twitterからデータを取得(または収集)する方法はいくつかあります。この記事では、TweepyとSnscrapeの2つの方法について説明します。
特定のトレンドトピックに関する人々からの公開会話や、特定のユーザーからのツイートをスクレイプする方法を学びます。
さて、これ以上面倒なことはせずに、始めましょう。
さて、各プラットフォームの実装に入る前に、各プラットフォームの違いと限界を把握してみましょう。
Tweepyは、TwitterAPIと統合するためのPythonライブラリです。TweepyはTwitterAPIに接続されているため、ツイートをスクレイピングするだけでなく、複雑なクエリを実行できます。これにより、TwitterAPIのすべての機能を利用できるようになります。
ただし、いくつかの欠点があります。たとえば、標準APIでは最大1週間のツイートしか収集できない(つまり、Tweepyでは1週間を超えるツイートの回復が許可されないため、履歴データの取得は許可されません)。
また、ユーザーのアカウントから取得できるツイートの数には制限があります。Tweepyの機能について詳しくは、こちらをご覧ください。
Snscrapeは、APIを使用せずにTwitterから情報を取得するためのもう1つのアプローチです。Snscrapeを使用すると、ユーザーのプロファイル、ツイートコンテンツ、ソースなどの基本情報をスクレイピングできます。
SnscrapeはTwitterだけでなく、Facebook、Instagramなどの他の著名なソーシャルメディアネットワークからコンテンツをスクレイピングすることもできます。
その利点は、取得できるツイートの数やツイートのウィンドウ(つまり、ツイートの日付範囲)に制限がないことです。したがって、Snscrapeを使用すると、古いデータを取得できます。
ただし、1つの欠点は、Tweepyの他のすべての機能が不足していることです。それでも、ツイートをスクレイピングするだけの場合は、Snscrapeで十分です。
2つのメソッドの違いが明確になったので、それらの実装を1つずつ見ていきましょう。
Tweepyの使用を開始する前に、まずTwitterのクレデンシャルの準備ができていることを確認する必要があります。これで、TweepyをAPIキーに接続して、スクレイピングを開始できます。
Twitterの資格情報をお持ちでない場合は、こちらからTwitter開発者アカウントに登録できます。TwitterAPIをどのように使用するかについての基本的な質問がいくつかあります。その後、実装を開始できます。
最初のステップは、ローカルマシンにTweepyライブラリをインストールすることです。これは、次のように入力することで実行できます。
pip install git+https://github.com/tweepy/tweepy.git
Tweepyライブラリをインストールしたので、john
Twitterで呼び出されたユーザーから100件のツイートを取得してみましょう。これを可能にする完全なコード実装を見て、何が起こっているのかを把握できるように詳細に説明します。
import tweepyconsumer_key = "XXXX" #Your API/Consumer key consumer_secret = "XXXX" #Your API/Consumer Secret Keyaccess_token = "XXXX" #Your Access token keyaccess_token_secret = "XXXX" #Your Access token Secret key#Pass in our twitter API authentication keyauth = tweepy.OAuth1UserHandler( consumer_key, consumer_secret, access_token, access_token_secret)#Instantiate the tweepy APIapi = tweepy.API(auth, wait_on_rate_limit=True)username = "john"no_of_tweets =100try: #The number of tweets we want to retrieved from the user tweets = api.user_timeline(screen_name=username, count=no_of_tweets) #Pulling Some attributes from the tweet attributes_container = [[tweet.created_at, tweet.favorite_count,tweet.source, tweet.text] for tweet in tweets] #Creation of column list to rename the columns in the dataframe columns = ["Date Created", "Number of Likes", "Source of Tweet", "Tweet"] #Creation of Dataframe tweets_df = pd.DataFrame(attributes_container, columns=columns)except BaseException as e: print('Status Failed On,',str(e)) time.sleep(3)
次に、上記のブロックのコードの各部分を見ていきましょう。
import tweepyconsumer_key = "XXXX" #Your API/Consumer key consumer_secret = "XXXX" #Your API/Consumer Secret Keyaccess_token = "XXXX" #Your Access token keyaccess_token_secret = "XXXX" #Your Access token Secret key#Pass in our twitter API authentication keyauth = tweepy.OAuth1UserHandler( consumer_key, consumer_secret, access_token, access_token_secret)#Instantiate the tweepy APIapi = tweepy.API(auth, wait_on_rate_limit=True)
上記のコードでは、Tweepyライブラリをコードにインポートしてから、Twitterクレデンシャルを格納する変数をいくつか作成しました(Tweepy認証ハンドラーには4つのTwitterクレデンシャルが必要です)。次に、それらの変数をTweepy認証ハンドラーに渡し、別の変数に保存します。
次に、呼び出しの最後のステートメントは、Tweepy APIをインスタンス化し、requireパラメーターを渡した場所です。
username = "john"no_of_tweets =100try: #The number of tweets we want to retrieved from the user tweets = api.user_timeline(screen_name=username, count=no_of_tweets) #Pulling Some attributes from the tweet attributes_container = [[tweet.created_at, tweet.favorite_count,tweet.source, tweet.text] for tweet in tweets] #Creation of column list to rename the columns in the dataframe columns = ["Date Created", "Number of Likes", "Source of Tweet", "Tweet"] #Creation of Dataframe tweets_df = pd.DataFrame(attributes_container, columns=columns)except BaseException as e: print('Status Failed On,',str(e))
上記のコードでは、ツイートを取得するユーザーの名前(Twitterでは@name)と、ツイートの数を作成しました。次に、より効果的な方法でエラーをキャッチするのに役立つ例外ハンドラーを作成しました。
その後api.user_timeline()
、パラメータで選択したユーザーによって投稿された最新のツイートのコレクションと、screen_name
取得するツイートの数が返されます。
次のコード行では、各ツイートから取得する属性をいくつか渡して、リストに保存しました。ツイートから取得できるその他の属性を確認するには、こちらをお読みください。
コードの最後のチャンクで、データフレームを作成し、作成した列の名前とともに作成したリストを渡しました。
列名は、属性コンテナにどのように渡したか(つまり、ツイートから属性を取得するときにリストでこれらの属性をどのように渡したか)の順序である必要があることに注意してください。
私が説明した手順を正しく実行した場合は、次のようになります。
著者による画像
これで完了です。Snscrapeの実装に移る前に、もう1つの例を見ていきましょう。
この方法では、検索に基づいてツイートを取得します。あなたはこのようにそれを行うことができます:
import tweepyconsumer_key = "XXXX" #Your API/Consumer key consumer_secret = "XXXX" #Your API/Consumer Secret Keyaccess_token = "XXXX" #Your Access token keyaccess_token_secret = "XXXX" #Your Access token Secret key#Pass in our twitter API authentication keyauth = tweepy.OAuth1UserHandler( consumer_key, consumer_secret, access_token, access_token_secret)#Instantiate the tweepy APIapi = tweepy.API(auth, wait_on_rate_limit=True)search_query = "sex for grades"no_of_tweets =150try: #The number of tweets we want to retrieved from the search tweets = api.search_tweets(q=search_query, count=no_of_tweets) #Pulling Some attributes from the tweet attributes_container = [[tweet.user.name, tweet.created_at, tweet.favorite_count, tweet.source, tweet.text] for tweet in tweets] #Creation of column list to rename the columns in the dataframe columns = ["User", "Date Created", "Number of Likes", "Source of Tweet", "Tweet"] #Creation of Dataframe tweets_df = pd.DataFrame(attributes_container, columns=columns)except BaseException as e: print('Status Failed On,',str(e))
api.user_timeline()
上記のコードは、APIメソッドをからに変更したことを除いて、前のコードと似ていますapi.search_tweets()
。tweet.user.name
属性コンテナリストにも追加しました。
上記のコードでは、2つの属性を渡したことがわかります。これは、を渡すだけではtweet.user
、辞書のユーザーオブジェクトのみが返されるためです。したがって、ユーザーオブジェクトから取得する別の属性である。も渡す必要がありますname
。
ここに移動して、ユーザーオブジェクトから取得できる追加の属性のリストを確認できます。これを実行すると、次のようなものが表示されます。
著者による画像。
了解しました。これでTweepyの実装はほぼ完了です。取得できるツイートの数には制限があり、Tweepyを使用して7日以上経過したツイートを取得することはできません。
前述したように、SnscrapeはそれにアクセスするためにTwitterのクレデンシャル(APIキー)を必要としません。取得できるツイートの数にも制限はありません。
ただし、この例では、前の例と同じツイートを取得しますが、代わりにSnscrapeを使用します。
Snscrapeを使用するには、最初にそのライブラリをPCにインストールする必要があります。次のように入力すると、次のように入力できます。
pip3 install git+https://github.com/JustAnotherArchivist/snscrape.git
Snscrapeには、Twitterからツイートを取得するための2つの方法が含まれています。コマンドラインインターフェイス(CLI)とPythonラッパーです。Python Wrapperは現在文書化されていないことを覚えておいてください。ただし、試行錯誤を繰り返すことで解決できます。
この例では、CLIメソッドよりも直感的であるため、Pythonラッパーを使用します。ただし、コードに行き詰まった場合は、いつでもGitHubコミュニティに支援を求めることができます。寄稿者は喜んでお手伝いします。
特定のユーザーからツイートを取得するには、次のようにします。
import snscrape.modules.twitter as sntwitterimport pandas as pd# Created a list to append all tweet attributes(data)attributes_container = []# Using TwitterSearchScraper to scrape data and append tweets to listfor i,tweet in enumerate(sntwitter.TwitterSearchScraper('from:john').get_items()): if i>100: break attributes_container.append([tweet.date, tweet.likeCount, tweet.sourceLabel, tweet.content]) # Creating a dataframe from the tweets list above tweets_df = pd.DataFrame(attributes_container, columns=["Date Created", "Number of Likes", "Source of Tweet", "Tweets"])
一見理解できないかもしれないコードのいくつかを見てみましょう:
for i,tweet in enumerate(sntwitter.TwitterSearchScraper('from:john').get_items()): if i>100: break attributes_container.append([tweet.date, tweet.likeCount, tweet.sourceLabel, tweet.content]) # Creating a dataframe from the tweets list above tweets_df = pd.DataFrame(attributes_container, columns=["Date Created", "Number of Likes", "Source of Tweet", "Tweets"])
上記のコードでは、sntwitter.TwitterSearchScaper
渡したユーザー(john)の名前からツイートのオブジェクトを返します。
前述したように、Snscrapeにはツイートの数に制限がないため、そのユーザーからのツイートの数は返されます。これを支援するために、オブジェクトを反復処理する列挙関数を追加し、カウンターを追加して、ユーザーからの最新の100件のツイートにアクセスできるようにする必要があります。
各ツイートから取得した属性構文は、Tweepyのものと同じように見えることがわかります。これらは、MartinBeckによってキュレーションされたSnscrapeツイートから取得できる属性のリストです。
クレジット:Martin Beck
Snscrapeライブラリはまだ開発中であるため、さらに属性が追加される可能性があります。たとえば上の画像のように、source
はに置き換えられましたsourceLabel
。パスのみを渡すとsource
、オブジェクトが返されます。
上記のコードを実行すると、次のようなものも表示されます。
著者による画像
次に、検索によるスクレイピングについても同じようにします。
import snscrape.modules.twitter as sntwitterimport pandas as pd# Creating list to append tweet data toattributes_container = []# Using TwitterSearchScraper to scrape data and append tweets to listfor i,tweet in enumerate(sntwitter.TwitterSearchScraper('sex for grades since:2021-07-05 until:2022-07-06').get_items()): if i>150: break attributes_container.append([tweet.user.username, tweet.date, tweet.likeCount, tweet.sourceLabel, tweet.content]) # Creating a dataframe to load the listtweets_df = pd.DataFrame(attributes_container, columns=["User", "Date Created", "Number of Likes", "Source of Tweet", "Tweet"])
繰り返しになりますが、Snscrapeを使用して多くの履歴データにアクセスできます(Tweepyとは異なり、標準APIは7日を超えることはできません。プレミアムAPIは30日です)。したがって、検索を開始する日付と終了する日付をsntwitter.TwitterSearchScraper()
メソッドに渡すことができます。
前のコードで行ったことは、基本的に前に説明したことです。覚えておくべき唯一のことは、Pythonの範囲関数と同様に機能するまで(つまり、最後の整数を除外する)ということです。したがって、今日からツイートを取得する場合は、今日の翌日を「until」パラメーターに含める必要があります。
著者の画像。
これで、Snscrapeを使用してツイートをスクレイピングする方法もわかりました。
それぞれの方法がどのように機能するかを見てきたので、いつどの方法を使用するのか疑問に思われるかもしれません。
ええと、それぞれの方法をいつ利用するかについての普遍的な規則はありません。すべては問題の好みとあなたのユースケースに帰着します。
無限のツイートを取得したい場合は、Snscrapeを使用する必要があります。ただし、Snscrapeが提供できない追加機能(ジオロケーションなど)を使用する場合は、必ずTweepyを使用する必要があります。Twitter APIと直接統合されており、完全な機能を提供します。
それでも、Snscrapeは基本的なスクレイピングに最も一般的に使用される方法です。
結論
この記事では、TweepyとSnscrapeを使用してPythonからデータをスクレイピングする方法を学びました。しかし、これは各アプローチがどのように機能するかについての簡単な概要にすぎませんでした。詳細については、Webを探索して詳細を確認してください。
追加情報が必要な場合に使用できる便利なリソースをいくつか紹介しました。読んでくれてありがとう。
ソース:https ://www.freecodecamp.org/news/python-web-scraping-tutorial/
1657769520
Si vous êtes un passionné de données, vous conviendrez probablement que l'une des sources les plus riches de données du monde réel est les médias sociaux. Des sites comme Twitter regorgent de données.
Vous pouvez utiliser les données que vous pouvez obtenir des médias sociaux de plusieurs façons, comme l'analyse des sentiments (analyser les pensées des gens) sur une question ou un domaine d'intérêt spécifique.
Il existe plusieurs façons de récupérer (ou de collecter) des données sur Twitter. Et dans cet article, nous examinerons deux de ces méthodes : utiliser Tweepy et Snscrape.
Nous apprendrons une méthode pour extraire les conversations publiques des personnes sur un sujet de tendance spécifique, ainsi que les tweets d'un utilisateur particulier.
Maintenant, sans plus tarder, commençons.
Maintenant, avant d'aborder l'implémentation de chaque plateforme, essayons de saisir les différences et les limites de chaque plateforme.
Tweepy est une bibliothèque Python pour l'intégration avec l'API Twitter. Parce que Tweepy est connecté à l'API Twitter, vous pouvez effectuer des requêtes complexes en plus de gratter des tweets. Il vous permet de profiter de toutes les fonctionnalités de l'API Twitter.
Mais il y a quelques inconvénients - comme le fait que son API standard ne vous permet de collecter des tweets que pendant une semaine maximum (c'est-à-dire que Tweepy ne permet pas la récupération des tweets au-delà d'une fenêtre d'une semaine, donc la récupération des données historiques n'est pas autorisée).
En outre, il existe des limites au nombre de tweets que vous pouvez récupérer à partir du compte d'un utilisateur. Vous pouvez en savoir plus sur les fonctionnalités de Tweepy ici .
Snscrape est une autre approche pour extraire des informations de Twitter qui ne nécessite pas l'utilisation d'une API. Snscrape vous permet de récupérer des informations de base telles que le profil d'un utilisateur, le contenu du tweet, la source, etc.
Snscrape ne se limite pas à Twitter, mais peut également récupérer le contenu d'autres réseaux sociaux importants tels que Facebook, Instagram et autres.
Ses avantages sont qu'il n'y a pas de limites au nombre de tweets que vous pouvez récupérer ou à la fenêtre de tweets (c'est-à-dire la plage de dates des tweets). Ainsi, Snscrape vous permet de récupérer d'anciennes données.
Mais le seul inconvénient est qu'il lui manque toutes les autres fonctionnalités de Tweepy – cependant, si vous ne voulez gratter que des tweets, Snscrape suffirait.
Maintenant que nous avons clarifié la distinction entre les deux méthodes, passons en revue leur implémentation une par une.
Avant de commencer à utiliser Tweepy, nous devons d'abord nous assurer que nos identifiants Twitter sont prêts. Avec cela, nous pouvons connecter Tweepy à notre clé API et commencer à gratter.
Si vous n'avez pas d'informations d'identification Twitter, vous pouvez créer un compte de développeur Twitter en vous rendant ici . On vous posera quelques questions de base sur la façon dont vous avez l'intention d'utiliser l'API Twitter. Après cela, vous pouvez commencer la mise en œuvre.
La première étape consiste à installer la bibliothèque Tweepy sur votre machine locale, ce que vous pouvez faire en tapant :
pip install git+https://github.com/tweepy/tweepy.git
Maintenant que nous avons installé la bibliothèque Tweepy, récupérons 100 tweets d'un utilisateur appelé john
sur Twitter. Nous examinerons l'implémentation complète du code qui nous permettra de faire cela et en discuterons en détail afin que nous puissions comprendre ce qui se passe :
import tweepy
consumer_key = "XXXX" #Your API/Consumer key
consumer_secret = "XXXX" #Your API/Consumer Secret Key
access_token = "XXXX" #Your Access token key
access_token_secret = "XXXX" #Your Access token Secret key
#Pass in our twitter API authentication key
auth = tweepy.OAuth1UserHandler(
consumer_key, consumer_secret,
access_token, access_token_secret
)
#Instantiate the tweepy API
api = tweepy.API(auth, wait_on_rate_limit=True)
username = "john"
no_of_tweets =100
try:
#The number of tweets we want to retrieved from the user
tweets = api.user_timeline(screen_name=username, count=no_of_tweets)
#Pulling Some attributes from the tweet
attributes_container = [[tweet.created_at, tweet.favorite_count,tweet.source, tweet.text] for tweet in tweets]
#Creation of column list to rename the columns in the dataframe
columns = ["Date Created", "Number of Likes", "Source of Tweet", "Tweet"]
#Creation of Dataframe
tweets_df = pd.DataFrame(attributes_container, columns=columns)
except BaseException as e:
print('Status Failed On,',str(e))
time.sleep(3)
Passons maintenant en revue chaque partie du code dans le bloc ci-dessus.
import tweepy
consumer_key = "XXXX" #Your API/Consumer key
consumer_secret = "XXXX" #Your API/Consumer Secret Key
access_token = "XXXX" #Your Access token key
access_token_secret = "XXXX" #Your Access token Secret key
#Pass in our twitter API authentication key
auth = tweepy.OAuth1UserHandler(
consumer_key, consumer_secret,
access_token, access_token_secret
)
#Instantiate the tweepy API
api = tweepy.API(auth, wait_on_rate_limit=True)
Dans le code ci-dessus, nous avons importé la bibliothèque Tweepy dans notre code, puis nous avons créé des variables dans lesquelles nous stockons nos informations d'identification Twitter (le gestionnaire d'authentification Tweepy nécessite quatre de nos informations d'identification Twitter). Nous transmettons donc ces variables au gestionnaire d'authentification Tweepy et les enregistrons dans une autre variable.
Ensuite, la dernière instruction d'appel est celle où nous avons instancié l'API Tweepy et transmis les paramètres requis.
username = "john"
no_of_tweets =100
try:
#The number of tweets we want to retrieved from the user
tweets = api.user_timeline(screen_name=username, count=no_of_tweets)
#Pulling Some attributes from the tweet
attributes_container = [[tweet.created_at, tweet.favorite_count,tweet.source, tweet.text] for tweet in tweets]
#Creation of column list to rename the columns in the dataframe
columns = ["Date Created", "Number of Likes", "Source of Tweet", "Tweet"]
#Creation of Dataframe
tweets_df = pd.DataFrame(attributes_container, columns=columns)
except BaseException as e:
print('Status Failed On,',str(e))
Dans le code ci-dessus, nous avons créé le nom de l'utilisateur (le @name dans Twitter) dont nous voulons récupérer les tweets ainsi que le nombre de tweets. Nous avons ensuite créé un gestionnaire d'exceptions pour nous aider à détecter les erreurs de manière plus efficace.
Après cela, le api.user_timeline()
renvoie une collection des tweets les plus récents publiés par l'utilisateur que nous avons choisi dans le screen_name
paramètre et le nombre de tweets que vous souhaitez récupérer.
Dans la ligne de code suivante, nous avons transmis certains attributs que nous souhaitons récupérer de chaque tweet et les avons enregistrés dans une liste. Pour voir plus d'attributs que vous pouvez récupérer à partir d'un tweet, lisez ceci .
Dans le dernier morceau de code, nous avons créé une trame de données et transmis la liste que nous avons créée avec les noms de la colonne que nous avons créée.
Notez que les noms de colonne doivent être dans l'ordre de la façon dont vous les avez passés dans le conteneur d'attributs (c'est-à-dire, comment vous avez passé ces attributs dans une liste lorsque vous récupérez les attributs du tweet).
Si vous avez correctement suivi les étapes que j'ai décrites, vous devriez avoir quelque chose comme ceci :
Image de l'auteur
Maintenant que nous avons terminé, passons en revue un autre exemple avant de passer à l'implémentation de Snscrape.
Dans cette méthode, nous allons récupérer un tweet basé sur une recherche. Vous pouvez le faire comme ceci :
import tweepy
consumer_key = "XXXX" #Your API/Consumer key
consumer_secret = "XXXX" #Your API/Consumer Secret Key
access_token = "XXXX" #Your Access token key
access_token_secret = "XXXX" #Your Access token Secret key
#Pass in our twitter API authentication key
auth = tweepy.OAuth1UserHandler(
consumer_key, consumer_secret,
access_token, access_token_secret
)
#Instantiate the tweepy API
api = tweepy.API(auth, wait_on_rate_limit=True)
search_query = "sex for grades"
no_of_tweets =150
try:
#The number of tweets we want to retrieved from the search
tweets = api.search_tweets(q=search_query, count=no_of_tweets)
#Pulling Some attributes from the tweet
attributes_container = [[tweet.user.name, tweet.created_at, tweet.favorite_count, tweet.source, tweet.text] for tweet in tweets]
#Creation of column list to rename the columns in the dataframe
columns = ["User", "Date Created", "Number of Likes", "Source of Tweet", "Tweet"]
#Creation of Dataframe
tweets_df = pd.DataFrame(attributes_container, columns=columns)
except BaseException as e:
print('Status Failed On,',str(e))
Le code ci-dessus est similaire au code précédent, sauf que nous avons modifié la méthode API de api.user_timeline()
à api.search_tweets()
. Nous avons également ajouté tweet.user.name
à la liste des conteneurs d'attributs.
Dans le code ci-dessus, vous pouvez voir que nous avons transmis deux attributs. En effet, si nous ne transmettons que tweet.user
, cela ne renverra qu'un objet utilisateur dictionnaire. Nous devons donc également transmettre un autre attribut que nous voulons récupérer à partir de l'objet utilisateur, qui est name
.
Vous pouvez aller ici pour voir une liste d'attributs supplémentaires que vous pouvez récupérer à partir d'un objet utilisateur. Maintenant, vous devriez voir quelque chose comme ceci une fois que vous l'avez exécuté :
Image de l'auteur.
Très bien, cela termine à peu près la mise en œuvre de Tweepy. N'oubliez pas qu'il y a une limite au nombre de tweets que vous pouvez récupérer et que vous ne pouvez pas récupérer de tweets datant de plus de 7 jours avec Tweepy.
Comme je l'ai mentionné précédemment, Snscrape ne nécessite pas d'informations d'identification Twitter (clé API) pour y accéder. Il n'y a pas non plus de limite au nombre de tweets que vous pouvez récupérer.
Pour cet exemple, cependant, nous allons simplement récupérer les mêmes tweets que dans l'exemple précédent, mais en utilisant Snscrape à la place.
Pour utiliser Snscrape, nous devons d'abord installer sa bibliothèque sur notre PC. Vous pouvez le faire en tapant :
pip3 install git+https://github.com/JustAnotherArchivist/snscrape.git
Snscrape inclut deux méthodes pour obtenir des tweets de Twitter : l'interface de ligne de commande (CLI) et un Python Wrapper. Gardez simplement à l'esprit que le Python Wrapper n'est actuellement pas documenté - mais nous pouvons toujours nous débrouiller avec des essais et des erreurs.
Dans cet exemple, nous utiliserons le Wrapper Python car il est plus intuitif que la méthode CLI. Mais si vous êtes bloqué avec du code, vous pouvez toujours vous tourner vers la communauté GitHub pour obtenir de l'aide. Les contributeurs se feront un plaisir de vous aider.
Pour récupérer les tweets d'un utilisateur particulier, nous pouvons procéder comme suit :
import snscrape.modules.twitter as sntwitter
import pandas as pd
# Created a list to append all tweet attributes(data)
attributes_container = []
# Using TwitterSearchScraper to scrape data and append tweets to list
for i,tweet in enumerate(sntwitter.TwitterSearchScraper('from:john').get_items()):
if i>100:
break
attributes_container.append([tweet.date, tweet.likeCount, tweet.sourceLabel, tweet.content])
# Creating a dataframe from the tweets list above
tweets_df = pd.DataFrame(attributes_container, columns=["Date Created", "Number of Likes", "Source of Tweet", "Tweets"])
Passons en revue une partie du code que vous ne comprenez peut-être pas à première vue :
for i,tweet in enumerate(sntwitter.TwitterSearchScraper('from:john').get_items()):
if i>100:
break
attributes_container.append([tweet.date, tweet.likeCount, tweet.sourceLabel, tweet.content])
# Creating a dataframe from the tweets list above
tweets_df = pd.DataFrame(attributes_container, columns=["Date Created", "Number of Likes", "Source of Tweet", "Tweets"])
Dans le code ci-dessus, ce qu'il sntwitter.TwitterSearchScaper
fait est de renvoyer un objet de tweets à partir du nom de l'utilisateur que nous lui avons transmis (qui est john).
Comme je l'ai mentionné plus tôt, Snscrape n'a pas de limite sur le nombre de tweets, il renverra donc le nombre de tweets de cet utilisateur. Pour vous aider, nous devons ajouter la fonction d'énumération qui parcourra l'objet et ajoutera un compteur afin que nous puissions accéder aux 100 tweets les plus récents de l'utilisateur.
Vous pouvez voir que la syntaxe des attributs que nous obtenons de chaque tweet ressemble à celle de Tweepy. Voici la liste des attributs que nous pouvons obtenir du tweet Snscrape qui a été organisé par Martin Beck.
1 crédit
D'autres attributs pourraient être ajoutés, car la bibliothèque Snscrape est encore en développement. Comme par exemple dans l'image ci-dessus, source
a été remplacé par sourceLabel
. Si vous passez seulement source
, cela renverra un objet.
Si vous exécutez le code ci-dessus, vous devriez également voir quelque chose comme ceci :
Image de l'auteur
Faisons maintenant de même pour le scraping par recherche.
import snscrape.modules.twitter as sntwitter
import pandas as pd
# Creating list to append tweet data to
attributes_container = []
# Using TwitterSearchScraper to scrape data and append tweets to list
for i,tweet in enumerate(sntwitter.TwitterSearchScraper('sex for grades since:2021-07-05 until:2022-07-06').get_items()):
if i>150:
break
attributes_container.append([tweet.user.username, tweet.date, tweet.likeCount, tweet.sourceLabel, tweet.content])
# Creating a dataframe to load the list
tweets_df = pd.DataFrame(attributes_container, columns=["User", "Date Created", "Number of Likes", "Source of Tweet", "Tweet"])
Encore une fois, vous pouvez accéder à de nombreuses données historiques en utilisant Snscrape (contrairement à Tweepy, car son API standard ne peut pas dépasser 7 jours. L'API premium est de 30 jours.). Nous pouvons donc transmettre la date à partir de laquelle nous voulons commencer la recherche et la date à laquelle nous voulons qu'elle se termine dans la sntwitter.TwitterSearchScraper()
méthode.
Ce que nous avons fait dans le code précédent correspond essentiellement à ce dont nous avons discuté précédemment. La seule chose à garder à l'esprit est que until fonctionne de manière similaire à la fonction range en Python (c'est-à-dire qu'elle exclut le dernier entier). Donc, si vous souhaitez obtenir des tweets à partir d'aujourd'hui, vous devez inclure le jour d'après dans le paramètre "jusqu'à".
Image de l'auteur.
Maintenant, vous savez aussi comment gratter des tweets avec Snscrape !
Maintenant que nous avons vu comment chaque méthode fonctionne, vous vous demandez peut-être quand utiliser laquelle.
Eh bien, il n'y a pas de règle universelle pour savoir quand utiliser chaque méthode. Tout se résume à une préférence de matière et à votre cas d'utilisation.
Si vous souhaitez acquérir un nombre infini de tweets, vous devez utiliser Snscrape. Mais si vous souhaitez utiliser des fonctionnalités supplémentaires que Snscrape ne peut pas fournir (comme la géolocalisation, par exemple), vous devez absolument utiliser Tweepy. Il est directement intégré à l'API Twitter et fournit des fonctionnalités complètes.
Même ainsi, Snscrape est la méthode la plus couramment utilisée pour le grattage de base.
Conclusion
Dans cet article, nous avons appris à récupérer des données de Python à l'aide de Tweepy et Snscrape. Mais ce n'était qu'un bref aperçu du fonctionnement de chaque approche. Vous pouvez en savoir plus en explorant le Web pour obtenir des informations supplémentaires.
J'ai inclus quelques ressources utiles que vous pouvez utiliser si vous avez besoin d'informations supplémentaires. Merci pour la lecture.
Source : https://www.freecodecamp.org/news/python-web-scraping-tutorial/
1657765620
Si es un entusiasta de los datos, probablemente estará de acuerdo en que una de las fuentes más ricas de datos del mundo real son las redes sociales. Sitios como Twitter están llenos de datos.
Puede usar los datos que puede obtener de las redes sociales de varias maneras, como el análisis de sentimientos (análisis de los pensamientos de las personas) sobre un tema o campo de interés específico.
Hay varias formas de raspar (o recopilar) datos de Twitter. Y en este artículo, veremos dos de esas formas: usando Tweepy y Snscrape.
Aprenderemos un método para recopilar conversaciones públicas de personas sobre un tema de tendencia específico, así como tweets de un usuario en particular.
Ahora, sin más preámbulos, comencemos.
Ahora, antes de entrar en la implementación de cada plataforma, intentemos comprender las diferencias y los límites de cada plataforma.
Tweepy es una biblioteca de Python para integrarse con la API de Twitter. Debido a que Tweepy está conectado con la API de Twitter, puede realizar consultas complejas además de raspar tweets. Le permite aprovechar todas las capacidades de la API de Twitter.
Pero hay algunos inconvenientes, como el hecho de que su API estándar solo le permite recopilar tweets durante un máximo de una semana (es decir, Tweepy no permite la recuperación de tweets más allá de una ventana de una semana, por lo que no se permite la recuperación de datos históricos).
Además, hay límites en la cantidad de tweets que puede recuperar de la cuenta de un usuario. Puedes leer más sobre las funcionalidades de Tweepy aquí .
Snscrape es otro enfoque para extraer información de Twitter que no requiere el uso de una API. Snscrape le permite recopilar información básica, como el perfil de un usuario, el contenido del tweet, la fuente, etc.
Snscrape no se limita a Twitter, sino que también puede extraer contenido de otras redes sociales destacadas como Facebook, Instagram y otras.
Sus ventajas son que no hay límites para la cantidad de tweets que puede recuperar o la ventana de tweets (es decir, el rango de fechas de los tweets). Entonces Snscrape le permite recuperar datos antiguos.
Pero la única desventaja es que carece de todas las demás funcionalidades de Tweepy; aún así, si solo desea raspar tweets, Snscrape sería suficiente.
Ahora que hemos aclarado la distinción entre los dos métodos, repasemos su implementación uno por uno.
Antes de comenzar a usar Tweepy, primero debemos asegurarnos de que nuestras credenciales de Twitter estén listas. Con eso, podemos conectar Tweepy a nuestra clave API y comenzar a raspar.
Si no tiene credenciales de Twitter, puede registrarse para obtener una cuenta de desarrollador de Twitter yendo aquí . Se le harán algunas preguntas básicas sobre cómo pretende utilizar la API de Twitter. Después de eso, puede comenzar la implementación.
El primer paso es instalar la biblioteca Tweepy en su máquina local, lo que puede hacer escribiendo:
pip install git+https://github.com/tweepy/tweepy.git
Ahora que hemos instalado la biblioteca Tweepy, raspamos 100 tweets de un usuario llamado john
en Twitter. Veremos la implementación del código completo que nos permitirá hacer esto y lo discutiremos en detalle para que podamos comprender lo que está sucediendo:
import tweepy
consumer_key = "XXXX" #Your API/Consumer key
consumer_secret = "XXXX" #Your API/Consumer Secret Key
access_token = "XXXX" #Your Access token key
access_token_secret = "XXXX" #Your Access token Secret key
#Pass in our twitter API authentication key
auth = tweepy.OAuth1UserHandler(
consumer_key, consumer_secret,
access_token, access_token_secret
)
#Instantiate the tweepy API
api = tweepy.API(auth, wait_on_rate_limit=True)
username = "john"
no_of_tweets =100
try:
#The number of tweets we want to retrieved from the user
tweets = api.user_timeline(screen_name=username, count=no_of_tweets)
#Pulling Some attributes from the tweet
attributes_container = [[tweet.created_at, tweet.favorite_count,tweet.source, tweet.text] for tweet in tweets]
#Creation of column list to rename the columns in the dataframe
columns = ["Date Created", "Number of Likes", "Source of Tweet", "Tweet"]
#Creation of Dataframe
tweets_df = pd.DataFrame(attributes_container, columns=columns)
except BaseException as e:
print('Status Failed On,',str(e))
time.sleep(3)
Ahora repasemos cada parte del código en el bloque anterior.
import tweepy
consumer_key = "XXXX" #Your API/Consumer key
consumer_secret = "XXXX" #Your API/Consumer Secret Key
access_token = "XXXX" #Your Access token key
access_token_secret = "XXXX" #Your Access token Secret key
#Pass in our twitter API authentication key
auth = tweepy.OAuth1UserHandler(
consumer_key, consumer_secret,
access_token, access_token_secret
)
#Instantiate the tweepy API
api = tweepy.API(auth, wait_on_rate_limit=True)
En el código anterior, hemos importado la biblioteca Tweepy a nuestro código, luego hemos creado algunas variables donde almacenamos nuestras credenciales de Twitter (el controlador de autenticación de Tweepy requiere cuatro de nuestras credenciales de Twitter). Entonces pasamos esas variables al controlador de autenticación Tweepy y las guardamos en otra variable.
Luego, la última declaración de llamada es donde instanciamos la API de Tweepy y pasamos los parámetros requeridos.
username = "john"
no_of_tweets =100
try:
#The number of tweets we want to retrieved from the user
tweets = api.user_timeline(screen_name=username, count=no_of_tweets)
#Pulling Some attributes from the tweet
attributes_container = [[tweet.created_at, tweet.favorite_count,tweet.source, tweet.text] for tweet in tweets]
#Creation of column list to rename the columns in the dataframe
columns = ["Date Created", "Number of Likes", "Source of Tweet", "Tweet"]
#Creation of Dataframe
tweets_df = pd.DataFrame(attributes_container, columns=columns)
except BaseException as e:
print('Status Failed On,',str(e))
En el código anterior, creamos el nombre del usuario (el @nombre en Twitter) del que queremos recuperar los tweets y también la cantidad de tweets. Luego creamos un controlador de excepciones para ayudarnos a detectar errores de una manera más efectiva.
Después de eso, api.user_timeline()
devuelve una colección de los tweets más recientes publicados por el usuario que elegimos en el screen_name
parámetro y la cantidad de tweets que desea recuperar.
En la siguiente línea de código, pasamos algunos atributos que queremos recuperar de cada tweet y los guardamos en una lista. Para ver más atributos que puede recuperar de un tweet, lea esto .
En el último fragmento de código, creamos un marco de datos y pasamos la lista que creamos junto con los nombres de la columna que creamos.
Tenga en cuenta que los nombres de las columnas deben estar en la secuencia de cómo los pasó al contenedor de atributos (es decir, cómo pasó esos atributos en una lista cuando estaba recuperando los atributos del tweet).
Si seguiste correctamente los pasos que describí, deberías tener algo como esto:
Imagen por autor
Ahora que hemos terminado, repasemos un ejemplo más antes de pasar a la implementación de Snscrape.
En este método, recuperaremos un tweet basado en una búsqueda. Puedes hacerlo así:
import tweepy
consumer_key = "XXXX" #Your API/Consumer key
consumer_secret = "XXXX" #Your API/Consumer Secret Key
access_token = "XXXX" #Your Access token key
access_token_secret = "XXXX" #Your Access token Secret key
#Pass in our twitter API authentication key
auth = tweepy.OAuth1UserHandler(
consumer_key, consumer_secret,
access_token, access_token_secret
)
#Instantiate the tweepy API
api = tweepy.API(auth, wait_on_rate_limit=True)
search_query = "sex for grades"
no_of_tweets =150
try:
#The number of tweets we want to retrieved from the search
tweets = api.search_tweets(q=search_query, count=no_of_tweets)
#Pulling Some attributes from the tweet
attributes_container = [[tweet.user.name, tweet.created_at, tweet.favorite_count, tweet.source, tweet.text] for tweet in tweets]
#Creation of column list to rename the columns in the dataframe
columns = ["User", "Date Created", "Number of Likes", "Source of Tweet", "Tweet"]
#Creation of Dataframe
tweets_df = pd.DataFrame(attributes_container, columns=columns)
except BaseException as e:
print('Status Failed On,',str(e))
El código anterior es similar al código anterior, excepto que cambiamos el método API de api.user_timeline()
a api.search_tweets()
. También hemos agregado tweet.user.name
a la lista de contenedores de atributos.
En el código anterior, puede ver que pasamos dos atributos. Esto se debe a que si solo pasamos tweet.user
, solo devolvería un objeto de usuario de diccionario. Entonces, también debemos pasar otro atributo que queremos recuperar del objeto de usuario, que es name
.
Puede ir aquí para ver una lista de atributos adicionales que puede recuperar de un objeto de usuario. Ahora deberías ver algo como esto una vez que lo ejecutes:
Imagen por Autor.
Muy bien, eso casi concluye la implementación de Tweepy. Solo recuerda que hay un límite en la cantidad de tweets que puedes recuperar, y no puedes recuperar tweets de más de 7 días usando Tweepy.
Como mencioné anteriormente, Snscrape no requiere credenciales de Twitter (clave API) para acceder a él. Tampoco hay límite para la cantidad de tweets que puede obtener.
Para este ejemplo, sin embargo, solo recuperaremos los mismos tweets que en el ejemplo anterior, pero usando Snscrape en su lugar.
Para usar Snscrape, primero debemos instalar su biblioteca en nuestra PC. Puedes hacerlo escribiendo:
pip3 install git+https://github.com/JustAnotherArchivist/snscrape.git
Snscrape incluye dos métodos para obtener tweets de Twitter: la interfaz de línea de comandos (CLI) y Python Wrapper. Solo tenga en cuenta que Python Wrapper actualmente no está documentado, pero aún podemos salir adelante con prueba y error.
En este ejemplo, usaremos Python Wrapper porque es más intuitivo que el método CLI. Pero si te quedas atascado con algún código, siempre puedes recurrir a la comunidad de GitHub para obtener ayuda. Los colaboradores estarán encantados de ayudarte.
Para recuperar tweets de un usuario en particular, podemos hacer lo siguiente:
import snscrape.modules.twitter as sntwitter
import pandas as pd
# Created a list to append all tweet attributes(data)
attributes_container = []
# Using TwitterSearchScraper to scrape data and append tweets to list
for i,tweet in enumerate(sntwitter.TwitterSearchScraper('from:john').get_items()):
if i>100:
break
attributes_container.append([tweet.date, tweet.likeCount, tweet.sourceLabel, tweet.content])
# Creating a dataframe from the tweets list above
tweets_df = pd.DataFrame(attributes_container, columns=["Date Created", "Number of Likes", "Source of Tweet", "Tweets"])
Repasemos algunos de los códigos que quizás no entiendas a primera vista:
for i,tweet in enumerate(sntwitter.TwitterSearchScraper('from:john').get_items()):
if i>100:
break
attributes_container.append([tweet.date, tweet.likeCount, tweet.sourceLabel, tweet.content])
# Creating a dataframe from the tweets list above
tweets_df = pd.DataFrame(attributes_container, columns=["Date Created", "Number of Likes", "Source of Tweet", "Tweets"])
En el código anterior, lo que sntwitter.TwitterSearchScaper
hace es devolver un objeto de tweets del nombre del usuario que le pasamos (que es john).
Como mencioné anteriormente, Snscrape no tiene límites en la cantidad de tweets, por lo que devolverá la cantidad de tweets de ese usuario. Para ayudar con esto, necesitamos agregar la función de enumeración que iterará a través del objeto y agregará un contador para que podamos acceder a los 100 tweets más recientes del usuario.
Puede ver que la sintaxis de los atributos que obtenemos de cada tweet se parece a la de Tweepy. Esta es la lista de atributos que podemos obtener del tweet Snscrape que fue curado por Martin Beck.
Crédito: Martin Beck
Se pueden agregar más atributos, ya que la biblioteca Snscrape aún está en desarrollo. Como por ejemplo en la imagen de arriba, source
ha sido reemplazado por sourceLabel
. Si pasa solo source
devolverá un objeto.
Si ejecuta el código anterior, también debería ver algo como esto:
Imagen por autor
Ahora hagamos lo mismo para raspar por búsqueda.
import snscrape.modules.twitter as sntwitter
import pandas as pd
# Creating list to append tweet data to
attributes_container = []
# Using TwitterSearchScraper to scrape data and append tweets to list
for i,tweet in enumerate(sntwitter.TwitterSearchScraper('sex for grades since:2021-07-05 until:2022-07-06').get_items()):
if i>150:
break
attributes_container.append([tweet.user.username, tweet.date, tweet.likeCount, tweet.sourceLabel, tweet.content])
# Creating a dataframe to load the list
tweets_df = pd.DataFrame(attributes_container, columns=["User", "Date Created", "Number of Likes", "Source of Tweet", "Tweet"])
Nuevamente, puede acceder a una gran cantidad de datos históricos utilizando Snscrape (a diferencia de Tweepy, ya que su API estándar no puede exceder los 7 días. La API premium es de 30 días). Entonces podemos pasar la fecha a partir de la cual queremos comenzar la búsqueda y la fecha en la que queremos que finalice en el sntwitter.TwitterSearchScraper()
método.
Lo que hemos hecho en el código anterior es básicamente lo que discutimos antes. Lo único a tener en cuenta es que hasta funciona de manera similar a la función de rango en Python (es decir, excluye el último entero). Entonces, si desea obtener tweets de hoy, debe incluir el día después de hoy en el parámetro "hasta".
Imagen de Autor.
¡Ahora también sabes cómo raspar tweets con Snscrape!
Ahora que hemos visto cómo funciona cada método, es posible que se pregunte cuándo usar cuál.
Bueno, no existe una regla universal sobre cuándo utilizar cada método. Todo se reduce a una preferencia de materia y su caso de uso.
Si desea adquirir un sinfín de tweets, debe usar Snscrape. Pero si desea utilizar funciones adicionales que Snscrape no puede proporcionar (como la geolocalización, por ejemplo), definitivamente debería utilizar Tweepy. Se integra directamente con la API de Twitter y proporciona una funcionalidad completa.
Aun así, Snscrape es el método más utilizado para el raspado básico.
Conclusión
En este artículo, aprendimos cómo extraer datos de Python usando Tweepy y Snscrape. Pero esto fue solo una breve descripción de cómo funciona cada enfoque. Puede obtener más información explorando la web para obtener información adicional.
He incluido algunos recursos útiles que puede usar si necesita información adicional. Gracias por leer.
Fuente: https://www.freecodecamp.org/news/python-web-scraping-tutorial/