Javascript 无需身份验证即可以 JSON 格式获取 Twitter 提要

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13454287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:08:29  来源:igfitidea点击:

Get Twitter Feed as JSON without authentication

javascripttwitter

提问by SimonBarker

I wrote a small JavaScript a couple of years ago that grabbed a users (mine) most recent tweet and then parsed it out for display including links, date etc.

几年前我写了一个小的 JavaScript,它抓取了用户(我的)最近的推文,然后将其解析出来以显示,包括链接、日期等。

It used this json call to retrieve the tweets and it no longer works.

它使用这个 json 调用来检索推文,但它不再有效。

http://twitter.com/statuses/user_timeline/radfan.json

It now returns the error:

它现在返回错误:

{"errors":[{"message":"Sorry, that page does not exist","code":34}]}

I have looked at using the api version (code below) but this requires authentication which I would rather avoid having to do as it is just to display my latest tweet on my website which is public anyway on my profile page:

我已经看过使用 api 版本(下面的代码),但这需要身份验证,我宁愿避免这样做,因为它只是在我的网站上显示我的最新推文,无论如何在我的个人资料页面上都是公开的:

http://api.twitter.com/1/statuses/radfan.json

I haven't kept up with Twitter's API changes as I no longer really work with it, is there a way round this problem or is it no longer possible?

我没有跟上 Twitter 的 API 更改,因为我不再真正使用它,有没有办法解决这个问题,或者不再可能?

采纳答案by MarcoK

As you can see in the documentation, using the REST API you'll need OAuth Tokensin order to do this. Luckily, we can use the Search(which doesn't use OAuth) and use the from:[USERNAME]operator

正如您在文档中看到的那样,使用 REST API 您需要OAuth 令牌才能做到这一点。幸运的是,我们可以使用Search(不使用 OAuth)并使用from:[USERNAME]运算符

Example: http://search.twitter.com/search.json?q=from:marcofolio
Will give you a JSON object with tweets from that user, where

示例:http: //search.twitter.com/search.json
?q=from : marcofolio会给你一个带有来自该用户的推文的 JSON 对象,其中

object.results[0]

will give you the last tweet.

会给你最后一条推文。

回答by Dustin

Previously the Search APIwas the only Twitter API that didn't require some form of OAuth. Now it does require auth.

以前,搜索 API是唯一不需要某种形式的OAuth 的Twitter API 。现在它确实需要身份验证。

Twitter's Search APIis acquired from a third party acquisition - they rarely support it and are seemingly unenthused that it even exists. On top of that, there are many limitations to the payload, including but not limited to a severely reduced set of key:valuepairs in the JSONor XMLfile you get back.

Twitter 的搜索 API是从第三方收购中获得的——他们很少支持它,而且似乎对它的存在不感兴趣。最重要的是,有效载荷有许多限制,包括但不限于您返回的JSONXML文件中的一组严重减少的键:值对。

When I heard this, I was shocked. I spent a LONG time figuring out how to use the least amount of code to do a simple GETrequest (like displaying a timeline).

当我听到这句话时,我很震惊。我花了很长时间弄清楚如何使用最少的代码来执行简单的GET请求(例如显示时间线)。

I decided to go the OAuthroute to be able to ensure a relevant payload. You need a server-side language to do this. JavaScriptis visible to end users, and thus it's a bad idea to include the necessary keysand secretsin a .js file.

我决定走OAuth路线以确保相关的有效负载。您需要一种服务器端语言来执行此操作。JavaScript对最终用户可见,因此在 .js 文件中包含必要的密钥机密是一个坏主意。

I didn't want to use a big library so the answer for me was PHPand help from @Rivers' answer here. The answer below it by @lackovic10 describes how to include queries in your authentication.

我不想使用大库,所以我的答案是PHP和来自@Rivers 的答案here 的帮助。@lackovic10 下面的答案描述了如何在您的身份验证中包含查询。

I hope this helps others save time thinking about how to go about using Twitter's API with the new OAuthrequirement.

我希望这可以帮助其他人节省时间思考如何使用 Twitter 的 API 和新的OAuth要求。

回答by RafaSashi

You can access and scrape Twitter via advanced search without being logged in:

您无需登录即可通过高级搜索访问和抓取 Twitter:

GET request

获取请求

When performing a basic search request you get:

执行基本搜索请求时,您会得到:

https://twitter.com/search?q=Babylon%205&src=typd
  • q (our query encoded)
  • src (assumed to be the source of the query, i.e. typed)
  • q(我们的查询编码)
  • src(假设是查询的来源,即输入的)

by default, Twitter returns top 25 results, but if you click on allyou can get the realtime tweets:

默认情况下,Twitter 返回前 25 个结果,但如果您点击, all您可以获得实时推文:

https://twitter.com/search?f=realtime&q=Babylon%205&src=typd

JSON contents

JSON 内容

More Tweets are loaded on the page via AJAX:

更多推文通过 AJAX 加载到页面上:

https://twitter.com/i/search/timeline?f=realtime&q=Babylon%205&src=typd&include_available_features=1&include_entities=1&last_note_ts=85&max_position=TWEET-553069642609344512-553159310448918528-BD1UO2FFu9QAAAAAAAAETAAAAAcAAAASAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

Use max_positionto request the next tweets

使用max_position请求下一鸣叫

The following json array returns all you need to scrape the contents:

以下 json 数组返回抓取内容所需的所有内容:

https://twitter.com/i/search/timeline?f=realtime&q=Babylon%205&src=typd
  • has_more_items (bool)
  • items_html (html)
  • max_position (key)
  • refresh_cursor (key)
  • has_more_items (bool)
  • items_html (html)
  • 最大位置(键)
  • refresh_cursor(键)

DOM elements

DOM元素

Here comes a list of DOM elementsyou can use to extract

这是DOM elements您可以用来提取的列表

The authors twitter handle

作者推特句柄

div.original-tweet[data-tweet-id]   

The name of the author

作者姓名

div.original-tweet[data-name]

The user ID of the author

作者的用户名

div.original-tweet[data-user-id]    

Timestamp of the post

帖子的时间戳

span._timestamp[data-time]  

Timestamp of the post in ms

以毫秒为单位的帖子时间戳

span._timestamp[data-time-ms]

Text of Tweet

推文文字

p.tweet-text

Number of Retweets

转推次数

span.ProfileTweet-action–retweet > span.ProfileTweet-actionCount[data-tweet-stat-count] 

Number of Favo

Favo 的数量

span.ProfileTweet-action–favorite > span.ProfileTweet-actionCount[data-tweet-stat-count]    

Resources

资源

回答by cosmocatalano

If you're still looking for unauthenticated tweets in JSON, this should work: https://github.com/cosmocatalano/tweet-2-json

如果您仍在 JSON 中寻找未经身份验证的推文,这应该可行:https: //github.com/cosmocatalano/tweet-2-json

回答by Jon Olick

Here is a quick hack (really a hack, should be used with caution as its not future proof) which uses http://anyorigin.comto scrape twitter site for the latest tweets.

这是一个快速的 hack(真的是一个 hack,应该谨慎使用,因为它不是未来的证明)它使用http://anyorigin.com来抓取 twitter 站点以获取最新的推文。

http://codepen.io/JonOlick/pen/XJaXBd

http://codepen.io/JonOlick/pen/XJaXBd

It works by using anyorigin (you have to pay to use it) to grab the HTML. It then parses the HTML using jquery to extract out the relevant tweets.

它的工作原理是使用 anyorigin(您必须付费才能使用它)来抓取 HTML。然后它使用 jquery 解析 HTML 以提取出相关的推文。

Tweets on the mobile site use a div with the class .tweet-text, so this is pretty painless.

移动站点上的推文使用带有 .tweet-text 类的 div,因此这非常轻松。

The relevant code looks like this:

相关代码如下所示:

$.getJSON('http://anyorigin.com/get?url=mobile.twitter.com/JonOlick&callback=?', function(data){

  // Remap ... utf8 encoding to ascii. 
  var bar = data.contents;
  bar = bar.replace(/a|/g, '...');

  var el = $( '<div></div>' );
  el.html(bar);

  // Change all links to point back at twitter
  $('.twitter-atreply', el).each(function(i){
    $(this).attr('href', "https://twitter.com" + $(this).attr('href'))
  });

  // For all tweets
  $('.tweet-text', el).each(function(i){
    // We only care about the first 4 tweets
    if(i < 4) {
      var foo = $(this).html();
      $('#test').html($('#test').html() + "<div class=ProfileTweet><div class=ProfileTweet-contents>" + foo + "</div></div><br>");
    }
  });

});

回答by Fiach Reid

You can use a Twitter API wrapper, such as TweetJS.comwhich offers a limited set of the Twitter API's functionality, but does not require authentication. It's called like this;

您可以使用 Twitter API 包装器,例如TweetJS.com,它提供了一组有限的 Twitter API 功能,但不需要身份验证。是这样叫的;

TweetJs.ListTweetsOnUserTimeline("PetrucciMusic",
function (data) {
    console.log(data);
});

回答by Dorukcan Ki?in

You can use the twitter api v1 to take the tweets without using OAuth. For example: thislink turns @Hyman's last 100 tweets.

您可以使用 twitter api v1 在不使用 OAuth 的情况下获取推文。例如:链接会转换@Hyman 的最后 100 条推文。

The timeline documentation is here.

时间线文档在这里

回答by mcbjam

The method "GET statuses/user_timeline" need a user Authentification like you can see on the official documentation :

方法“GET statuses/user_timeline”需要用户身份验证,就像您在官方文档中看到的那样:

You can use the search method "GET search" wich not require authentification.

您可以使用不需要身份验证的搜索方法“GET 搜索”。

You have a code for starting here : http://jsfiddle.net/73L4c/6/

你有一个从这里开始的代码:http: //jsfiddle.net/73L4c/6/

function searchTwitter(query) {
    $.ajax({
        url: 'http://search.twitter.com/search.json?' + jQuery.param(query),
        dataType: 'jsonp',
        success: function(data) {
            var tweets = $('#tweets');
            tweets.html('');
            for (res in data['results']) {
                tweets.append('<div>' + data['results'][res]['from_user'] + ' wrote: <p>' + data['results'][res]['text'] + '</p></div><br />');
            }
        }
    });
}

$(document).ready(function() {
    $('#submit').click(function() {
        var params = {
            q: $('#query').val(),
            rpp: 5
        };
        // alert(jQuery.param(params));
        searchTwitter(params);
    });
})