Git Product home page Git Product logo

scrape-twitter's Introduction

scrape-twitter Build Status npm version

🐦 Access Twitter data without an API key

DEPRECATED: The next version of Twitter auto-generates all of the class names and therefore is going to be much more difficult to screen scrape. I might come up with a better solution...


This module provides command line interfaces to scrape: profiles, timelines, connections, likes, search and conversations.

It also exposes both streams and a promise returning function to help accessing Twitter in your own applications.

Real-time firehoses can be created using the companion module monitor-head-stream.

Features

  • Get Twitter data without being required to configure an API key.
  • Twitter can't constrain access as easily as they can to an API or an individual API key. Any constraints introduced would apply to their public site. A scraper can be fixed; you are no longer beholden to Twitter.
  • Grab timelines, whole conversations, profiles, connections, likes, etc.
  • Automatically pages to fetch all tweets.
  • Provides metadata on how tweet replies are linked together. e.g. isReplyToId

Example

Get profile

$ scrape-twitter profile sebinsua
# ...

Get timeline

$ scrape-twitter timeline nouswaves
# ...

Get likes

This command requires a valid login. It will check for the following environment variables: TWITTER_USERNAME, TWITTER_PASSWORD, TWITTER_KDT. But can also pick these up from a dotenv file at the path ~/.scrape-twitter. The first time you login you will be asked to store the TWITTER_KDT - this is used by Twitter to recognise your device.

$ scrape-twitter likes sebinsua
# ...

Get connections

This command also requires a valid login.

$ scrape-twitter connections sebinsua --type=following
# ...

Get conversation

$ scrape-twitter conversation ctbeiser 691766715835924484
# ...

Search

$ scrape-twitter search --query "from:afoolswisdom motivation" --type latest
# ...

Get list

$ scrape-twitter list nouswaves list
# ...

JSON interface plays nicely with CLI tools like jq, coreutils/gshuf and terminal-notifier

For example, a MOTD-like script might contain:

scrape-twitter search --query="from:afoolswisdom knowledge" | jq -r '.[].text' | gshuf -n 1 | terminal-notifier -title "Knowledge (MOTD)"

Install

With yarn:

yarn global add scrape-twitter

With npm:

npm install -g scrape-twitter

API

new TimelineStream(username: string, { retweets: boolean, replies: boolean, count: ?number })

Create a ReadableStream<Tweet> for the timeline of a username.

new LikeStream(username: string, { count: ?number, env: process.env })

Create a ReadableStream<Tweet> for the likes of a username.

new ConnectionStream(username: string, type: 'following' | 'followers', process.env)

Create a ReadableStream<UserConnection> for the connections of a username.

new ConversationStream(username: string, id: string, { count: ?number })

Create a ReadableStream<Tweet> for the conversation that belongs to a username and tweet id.

new ThreadedConversationStream(id: string)

Create a ReadableStream<Tweet> for the thread that belongs to a tweet id.

new TweetStream(query: string, type: 'top' | 'latest', { count: ?number })

Create a ReadableStream<Tweet> for the tweets that match a query and type.

new ListStream(username: string, list: string, { count: ?number })

Create a ReadableStream<Tweet> for the username's list.

getUserProfile(username: string)

Get a Promise<UserProfile> for a particular username.

scrape-twitter's People

Contributors

adoussot avatar bvallelunga avatar garrylachman avatar mikebull avatar sebinsua avatar voileexperiments avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

scrape-twitter's Issues

login issue

vi eddited ~/,scrape-twitter

added:

TWITTER_USERNAME = 'username'
TWITTER_PASSWORD = 'password'

tried sample command:

scrape-twitter likes sebinsua ###(or another random account)
receive following error msg:

Error: An active login is required for this API call
at checkStatus (/usr/local/lib/node_modules/scrape-twitter/dist/lib/query.js:11:17)
at process._tickCallback (node.js:368:9)

login shld have been succesfull (if i try same account with a wrong password i get a wrong password/username error)
how to proceed? ty

Getting follower lists

Hello i keep getting this error when trying to scrape for followers / likes:

FetchError: invalid json response body at https://twitter.com/account/access reason: Unexpected token < in JSON at position 0
at C:\Users.......\npm\node_modules\scrape-twitter\node_modules\node-fetch\lib\body.js:48:31
at
at process._tickCallback (internal/process/next_tick.js:188:7)

Am relatively new to node.js, so i'm not too sure how to even start solving it. Pardon my noobness. Any help would be much appreciated!

Thanks heaps

UTF-8 Tweets encoding

I have a problem with reading tweets, when i scrape it, it's not decoded in UTF-8 and special chars like á,ž are showed like á,Ä�, etc.. How to decode it?

Anyway, Good job! :) Amazing project 👍

Seems like scrape-twitter is not scraping the latest tweets anymore...?

When I do "scrape-twitter timeline realDonaldTrump | head -n 5" I get this:

[
{"screenName":"realDonaldTrump","id":"967564998238142471","time":"2018-02-25T01:00:46.000Z","isRetweet":false,"isPinned":false,"isReplyTo":false,"text":"I will be interviewed by @JudgeJeanine on @foxnews at 9:00 P.M. Enjoy!","userMentions":[{"screenName":"JudgeJeanine","indices":[25,38]},{"screenName":"FoxNews","indices":[42,50]}],"hashtags":[],"images":[],"urls":[],"replyCount":19726,"retweetCount":8033,"favoriteCount":43376},
{"screenName":"realDonaldTrump","id":"967563946063523840","time":"2018-02-25T00:56:35.000Z","isRetweet":false,"isPinned":false,"isReplyTo":false,"text":"“Congressman Schiff omitted and distorted key facts” @foxnews So, what else is new. He is a total phony!","userMentions":[{"screenName":"FoxNews","indices":[53,61]}],"hashtags":[],"images":[],"urls":[],"replyCount":24448,"retweetCount":17791,"favoriteCount":67794},
{"screenName":"realDonaldTrump","id":"967545724362739712","time":"2018-02-24T23:44:11.000Z","isRetweet":false,"isPinned":false,"isReplyTo":false,"text":"“Russians had no compromising information on Donald Trump” @foxnews Of course not, because there is none, and never was. This whole Witch Hunt is an illegal disgrace...and Obama did nothing about Russia!","userMentions":[{"screenName":"FoxNews","indices":[59,67]}],"hashtags":[],"images":[],"urls":[],"replyCount":27619,"retweetCount":17677,"favoriteCount":65428},
{"screenName":"realDonaldTrump","id":"967539664692350977","time":"2018-02-24T23:20:06.000Z","isRetweet":false,"isPinned":false,"isReplyTo":false,"text":"Dem Memo: FBI did not disclose who the clients were - the Clinton Campaign and the DNC. Wow!","userMentions":[],"hashtags":[],"images":[],"urls":[],"replyCount":13575,"retweetCount":20119,"favoriteCount":71728},
events.js:160
throw er; // Unhandled 'error' event
^

So the latest tweet is from a day ago. Any idea why that is?

Parser stripping suffix from number

I've noticed that when I scrape a popular Twitter profile with over ten thousand tweets/followers/following/etc, the numbers I get back from the scraper are usually much smaller than they should be.

After a bit of digging, it looks like the counts in parser.js are taking the suffixed value (i.e. 15.5k) and is stripping out non-numerical characters, so 155 is returned instead of 15500.

Instead of grabbing the suffixed number, do you see any issues with grabbing the data-count attribute, and using that instead? If not, I'll create a PR and send it your way.

Network Timeout Error On Large Queries

Hi,

I'm getting a FetchError: network timeout error. I found this goes away, if I add an exceptionally long timeout at the lines

return fetcher(resource, { agent: https.globalAgent })
and
return fetcher(resource, { agent: https.globalAgent })
, like:

    return fetcher(resource, { agent: https.globalAgent, timeout: 120000 })

It would be great to have a setting to set this timeout or make it part of the TweetStream options.

The script doesn't collect complete list of tweets for a conversation

The number of tweets returned for a given conversation is fewer than the actual tweets I found on the web browser for that conversation.

For the given example scrape-twitter conversation ctbeiser 691766715835924484 the script returns 8 tweets. However, there are more tweets looking at https://twitter.com/ctbeiser/status/691766715835924484 on the web browser.

Could you leave any contact to you?

I wanna talk with you about something regarding to your repo and to do it faster and easier could you please give me any discord/twitter or smth like that to communicate?

scrape conversation of infinite scrolling

I have a long conversation to scrape, but it seems that the scrape-twitter conversation command only scrape the first page of the conversation. May I know if you have any function to allow scraping the twitter conversation of infinite scrolling. The conversation I am going to scrape is only shown completely after about 13 scroll. Thanks

Hexadecimal handles are converted to decimal numbers before scraping

Steps to reproduce:

scrape-twitter profile [0xdeadbade, 0xabad1dea, ...] 

Stack trace:

/usr/lib/node_modules/scrape-twitter/dist/lib/cli-utils.js:11
  return (username || '').replace('@', '');
                          ^

TypeError: (username || "").replace is not a function
    at Object.parseUsername (/usr/lib/node_modules/scrape-twitter/dist/lib/cli-utils.js:11:27)
    at Object.<anonymous> (/usr/lib/node_modules/scrape-twitter/dist/bin/scrape-twitter-profile.js:16:27)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/usr/lib/node_modules/scrape-twitter/bin/scrape-twitter-profile.js:4:1)

I've traced the culprit code to this line in minimist:

    for (var i = 0; i < args.length; i++) {
        var arg = args[i];
        
        if (/^--.+=/.test(arg)) {
            // ...
        }
        else {
            if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
                argv._.push(
                    flags.strings['_'] || !isNumber(arg) ? arg : Number(arg) // Bingo
                );
            }
    // ...
    }

// ... snip ...

function isNumber (x) {
    if (typeof x === 'number') return true;
    if (/^0x[0-9a-f]+$/i.test(x)) return true; // Bingo II: This Time, It's Hecadecimal
    return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
}

Unsure if I should file this issue there or here.

URLs always prefixed by last word of extraction text

The algorithm used to extract the URL is really poor. All URLs contain the last word of tweet text at the start of the url. Twitter has published its own module which contains all of their code for extracting stuff from text, including URLs called twitter-text, it's on GitHub.

Bug: Profile not loading

If I execute scrape-twitter profile realdonaldtrump
I get the following response:

{
  "screenName": "",
  "name": "",
  "bio": "",
  "userMentions": [],
  "hashtags": [],
  "urls": [],
  "location": "",
  "joinDate": "undefined-undefined-01T00:00:00.000Z",
  "tweetCount": 0,
  "followingCount": 0,
  "followerCount": 0,
  "likeCount": 0
}

But not the correct information

Invalid JSON when using "likes" function

I've configured my enviromental variables, but I'm getting this error, any idea?

invalid json response body at https://twitter.com/pmerj/likes/timeline?include_available_features=1&include_entities=1 reason: Unexpected token <
FetchError: invalid json response body at https://twitter.com/pmerj/likes/timeline?include_available_features=1&include_entities=1 reason: Unexpected token <
at /usr/local/lib/node_modules/scrape-twitter/node_modules/node-fetch/lib/body.js:48:31
at process._tickCallback (node.js:368:9)

fetchCookie(url, opts) throws unexpected token function

Hello, I just downloaded scrape-twitter and am using it for the first time. I am experiencing an error. Apologies if this is a newbie mistake on my part :

Every scrape command I issue returns this result

/root/.nvm/versions/node/v6.11.5/lib/node_modules/scrape-twitter/node_modules/fetch-cookie/index.js:11
  async function fetchCookie (url, opts) {
        ^^^^^^^^

SyntaxError: Unexpected token function
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/root/.nvm/versions/node/v6.11.5/lib/node_modules/scrape-twitter/dist/lib/twitter-login.js:10:28

It shouldn't matter for $ scrape-twitter profile ... and $ scrape-twitter conversation commands, but I have set my environment variables for TWITTER_USERNAME and TWITTER_PASSWORD. The application crashes as above before Twitter responds with a KDT, if I understand the documentation correctly.

Search –query doesn’t scroll the page anymore.

Search –query doesn’t scroll the page anymore. Only the first 20 results are returned and they are are all duplicated. I am trying to fox this … without success up to now. Twitter probably changed something.

Cannot login.

Trying to use for the first time and cannot login, I get this error:

Could not login with username and the password supplied
Error: Could not login with smhttr and the password supplied
    at C:\Users\Name\AppData\Roaming\npm\node_modules\scrape-twitter\dist\lib\twitter-login.js:84:15
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)

Which is from:

var location = response.headers.get('location') || '';
if (location.includes('error')) {
  debug('unable to login with ' + TWITTER_USERNAME);
  throw new Error('Could not login with ' + TWITTER_USERNAME + ' and the password supplied');
}

What do I do to fix this?

Get media from Tweet

Hello,
This script is amazing and works great and I have a one question.

How to get link to the media from Tweet?
Like.. I mean.. If in tweet is video.. How to get url for mp4? or how to detect If in tweet is video?

Thanks

Export to json or txt list

Hi!

I have been currently using the timeline function of the program. Is it possible to update the code by including a function which exports the results to a .json or .txt file.

Thank you very much for your attention.

TypeError: Path must be a string. Received undefined

I'm getting an error when importing scrape-twitter with require('scrape-twitter') which is being thrown by the expandHome function in the cli-utils.js file.

Trace:

TypeError: Path must be a string. Received undefined
    at assertPath (path.js:28:11)
    at join (path.js:1236:7)
    at expandHomeDir (/Users/Admin/Desktop/100x365/functions/node_modules/expand-home-dir/index.js:10:10)
    at Object.<anonymous> (/Users/Admin/Desktop/100x365/functions/node_modules/scrape-twitter/dist/lib/cli-utils.js:6:29)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)

Undefined profile output and timeline error

Getting these responses for profile and timeline (havent tested other commands just these two)

scrape-twitter profile sebinsua:
{ "screenName": "", "name": "", "bio": "", "userMentions": [], "hashtags": [], "urls": [], "location": "", "joinDate": "undefined-undefined-01T00:00:00.000Z", "tweetCount": 0, "followingCount": 0, "followerCount": 0, "likeCount": 0 }

scrape-twitter timeline nouswaves:

`invalid json response body at https://twitter.com/i/profiles/show/nouswaves/timeline?include_available_features=1&include_entities=1 reason: Unexpected token < in JSON at position 0
FetchError: invalid json response body at https://twitter.com/i/profiles/show/nouswaves/timeline?include_available_features=1&include_entities=1 reason: Unexpected token < in JSON at position 0
    at C:\Users\cooki\Desktop\bot\node_modules\scrape-twitter\node_modules\node-fetch\lib\body.js:48:31
    at processTicksAndRejections (internal/process/task_queues.js:97:5)

    Access Twitter data without an API key.

    Usage
      $ scrape-twitter <command>

    Commands
      profile       Get a user's profile.
      timeline      Get a user's timeline.
      likes         Get a user's likes.
      connections   Get a user's connections.
      conversation  Get a particular conversation.
      list          Get the timeline of a particular list.
      search        Query Twitter for matching tweets.`

idk but these look like accessing twitter issues. Does this project still work?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.