推特API(Twitter API)V2 用户关注、推文相关

        前面章节已经介绍使用code换取Token的整个流程了,这里不再重复阐述了,下面我们获取到用户token以后如何帮用户自动关注别人。需要参数关注者的用户ID(token授权用户)以及关注的目标用户ID。用户ID如何获取可以看上一章节获取用户信息里面就有用户ID参数。

1.引入相关依赖Maven

<dependency>
    <groupId>oauth.signpost</groupId>
    <artifactId>signpost-core</artifactId>
    <version>1.2.1.2</version>
</dependency>

<dependency>
    <groupId>oauth.signpost</groupId>
    <artifactId>signpost-commonshttp4</artifactId>
    <version>1.2.1.2</version>
</dependency>

<dependency>
    <groupId>com.twitter</groupId>
    <artifactId>twitter-api-java-sdk</artifactId>
    <version>1.1.4</version>
</dependency>

<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency><dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>29.0-jre</version>
</dependency>

2.相关的配置类

/**
 * 推特相关配置
 */
public class TwitterConfig {
 
    /**
     * 客户id和客户私钥
     */
    public static final String CLIENT_ID = "c3dqY111tjbnFPNDM6MTpjaQ";
    public static final String CLIENT_SECRET = "kf1119fmdeXZHpOV-fjv9umx55ZdccCkNONjea";
 
 
    /**
     * 应用KYE和私钥
     */
    public static final String CONSUMER_KEY = "lhyfiD111MffGeHMR";
    public static final String CONSUMER_SECRET = "BRNxnV5Lx111jtptduIkcwjB";
 
    /**
     * 应用的TOKEN
     */
    public static final String ACCESS_TOKEN = "14821111633-A8xyN5111FgkbStu";
    public static final String ACCESS_TOKEN_SECRET = "oZaKBphpoo111SZvzoXPAQ";
 
        /**
     * 用户 Bearer Token
     */
    public static final String BEARER_TOKEN = "AAAAAAAAAAAAAAAAAAAAAOwXswEAAAAAGLQE%2F%2BydboYofYWIsXeXYz%2FvwOM%3Dxyxysp8mTiT8j6feRoc0BshFaghbkC58VHMRtcdvo5WjkvyqKF";
 
}

3.根据用户token让用户关注开发者 

@Data
@Accessors(chain = true)
public class AttentionDto {

    /**
     * true 表示关注成功  false 表示关注失败(目标用户没有公开推文的情况,因为他们必须批准关注者请求)
     */
    private Boolean following;

    /**
     * 指示目标用户是否需要批准关注请求。请注意,只有当目标用户批准传入的关注者请求时,经过身份验证的用户才会关注目标用户  false就是正常的
     */
    private Boolean pending_follow;

}
  /**
     * 用户关注
     * @param token 授权换取的用户token
     * @param userId 用户自己的ID
     * @return
     * @throws Exception
     */
    public AttentionDto attention(String token, String userId) throws Exception {
        String urlAdress = "https://api.twitter.com/2/users/" + userId + "/following";
        URL url12 = new URL(urlAdress);
        HttpURLConnection connection = (HttpURLConnection) url12.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", "Bearer " + token);
        JSONObject requestBody = new JSONObject();
        //需要关注的用户ID
        requestBody.put("target_user_id", "148294855969111111");
        String requestBodyString = requestBody.toString();
        connection.setDoOutput(true);
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(requestBodyString.getBytes());
        outputStream.flush();
        outputStream.close();

        int responseCode = connection.getResponseCode();
        InputStream inputStream;
        if (responseCode >= 200 && responseCode < 400) {
            inputStream = connection.getInputStream();
        } else {
            inputStream = connection.getErrorStream();
        }

        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        StringBuilder responseBuilder = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            responseBuilder.append(line);
        }
        reader.close();
        String response = responseBuilder.toString();
        if(JSON.parseObject(response).get("data") != null){
            JSONObject json = JSON.parseObject(JSON.parseObject(response).get("data").toString());
            AttentionDto attentionDto = new AttentionDto();
            Object ret = json.get("following");
            attentionDto.setFollowing(Boolean.parseBoolean(ret == null ? "false" : ret.toString()));
            ret = json.get("pending_follow");
            attentionDto.setPending_follow(Boolean.parseBoolean(ret == null ? "false" : ret.toString()));
            return attentionDto;
        }
        return null;
    }

4.查询我的推文列表

 /**
     * 查询我的推文列表
     * @param tweetUserId
     * @param token
     * @param ttTweetsId  平台指定转推文的ID
     * @param maxResults = 5-10之间
     * @return
     */
    public Integer getTweetList(String tweetUserId,String token,Integer maxResults,String ttTweetsId){
        try {
            String httpUrl = "https://api.twitter.com/2/users/"+ tweetUserId + "/tweets?max_results="+maxResults;
            httpUrl += "&expansions=author_id,edit_history_tweet_ids,referenced_tweets.id&tweet.fields=created_at";
            // 只查用户当日的推文
            Instant currentTime = LocalDateTime.of(LocalDate.now(), LocalTime.MIN).toInstant(ZoneOffset.of("+8"));
            DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;
            String endTimeRFC3339 = formatter.format(currentTime);
            httpUrl += "&start_time="+endTimeRFC3339;
                // 构建请求 URL
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法和请求头
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Authorization", "Bearer " + token);
            // 发送请求
            int responseCode = connection.getResponseCode();
            Assert.isTrue(responseCode == HttpURLConnection.HTTP_OK, "get tweet error");
            Integer numer = 0;
            // 读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            JSONObject jsonObject = JSON.parseObject(response.toString());
            JSONArray jsonArray = (JSONArray) jsonObject.get("data");
            if(jsonArray == null){
                return numer;
            }
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject json = jsonArray.getJSONObject(i);
                JSONArray referencedTweets = json.getJSONArray("referenced_tweets");
                if(referencedTweets != null){
                        /*retweeted: 表示当前推文是转推(Retweet)的引用。
                        quoted: 表示当前推文是引用推文(Quote Tweet)的引用。
                        replied_to: 表示当前推文是回复(Reply)的引用。*/
                    //上个推文的id
                    String type = referencedTweets.getJSONObject(0).get("type").toString();
                    String id = referencedTweets.getJSONObject(0).get("id").toString();
                    if(type.equals("quoted") || type.equals("retweeted") && ttTweetsId.equals(id)){
                        //quoted 表示推文是引用
                        numer++;
                    }
                }
            }
            // 打印响应
            return numer;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }

5.查询那些用户进行了推文的转发

/**
     * 根据推文ID查询那些用户进行了转发
     * @param tweetId
     * @param token
     * @return
     */
    public String transmitUserList(String tweetId,String token){
        try {
            // 构建请求 URL
            URL url = new URL("https://api.twitter.com/2/tweets/"+tweetId+"/retweeted_by");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法和请求头
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Authorization", "Bearer " + token);

            // 发送请求
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                StringBuilder response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                // 打印响应
                return response.toString();
            } else {
                System.out.println("Failed to fetch data from Twitter API. Response code: " + responseCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

6.生成推文的访问链接

    /**
     * 生成推文转发链接
     * @param tweetsName   推特用户名   如:@123456
     * @param tweetsId     推文Id
     * @return
     */
    public String getTtTweetsUrl(String tweetsName,String tweetsId){
        //推文Id
        String url = "https://twitter.com/";
        //推特用户名
        url += tweetsName;
        url += "/status/" + tweetsId +"?s=20";
        return url;
    }

 

7.可以获取开发者的账号Bearer Token

/**
     * 获取开发者推特token
     * @return
     */
    public String getTwitterToken(){
        try {
            String consumerKey = URLEncoder.encode(TwitterConfig.CONSUMER_KEY, "UTF-8");
            String consumerSecret = URLEncoder.encode(TwitterConfig.CONSUMER_SECRET, "UTF-8");
            String credentials = consumerKey + ":" + consumerSecret;
            String base64Credentials = Base64.getEncoder().encodeToString(credentials.getBytes());
            //authorization_code、refresh_token、client_credentials
            String grantType = "client_credentials";
            URL url = new URL("https://api.twitter.com/oauth2/token");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Authorization", "Basic " + base64Credentials);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            String data = "grant_type=" + grantType +
                "&client_id="+TwitterConfig.CLIENT_ID+"&client_secret="+TwitterConfig.CLIENT_SECRET+"&code_verifier=challenge";
            connection.getOutputStream().write(data.getBytes("UTF-8"));

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // Extract bearer token from JSON response
            String jsonResponse = response.toString();
            JSONObject json = JSON.parseObject(jsonResponse);
            return json.get("access_token").toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

如果这篇文章在你一筹莫展的时候帮助到了你,可以请作者吃个棒棒糖🙂,如果有啥疑问或者需要完善的地方欢迎大家在下面留言或者私信作者优化改进。

<think>好的,我现在需要帮助用户解决如何使用Python或其他技术爬取Twitter数据的问题。用户之前可能已经询问过类似的问题,现在需要更详细的指导。首先,我得回顾一下系统级指令,确保回答符合格式要求,比如数学表达式用$...$,独立公式用$$...$$,并且生成相关问题。同时,要使用中,结构清晰,引用相关献。 首先,用户的需求是获取爬取推特数据的方法或工具,特别是用Python或其他技术。我需要整理现有的知识,结合之前提供的引用内容,虽然引用中的内容提到使用Python的库如requests、tweepy,以及R包,但用户这次更关注Python,所以重点放在Python工具上。 接下来,我需要分步骤说明,可能包括注册开发者账号、选择工具库、认证、数据获取等。同时,要确保代码示例正确,使用tweepy和requests库,可能需要给出两种方法。另外,用户可能需要异步爬取的例子,如使用aiohttp和asyncio,这在引用[1]中有提到,所以需要包含进去。 需要注意的是,用户可能遇到认证问题,比如如何获取API密钥,环境变量的管理(dotenv),这些在引用[1]中也提到过,要详细说明。此外,数据存储和分析部分,用pandas保存数据,这也是用户可能需要的。 然后,生成相关问题,比如如何提高爬取效率、绕过限制,或者处理数据的方法。这些问题应该与用户当前的问题相关,帮助他们进一步探索。 现在要检查是否符合所有格式要求:行内数学表达式是否正确使用,如无数学内容可能不需要,但如果有变量或术语,可能需要用$...$。独立公式如果有的话要用$$...$$,但这里可能不太涉及。代码块要用正确的语法,Python代码要正确缩进,比如示例中的快速排序代码。 最后,确保引用的标记正确添加,引用[1]和引用[2]中的内容要自然地融入回答中,比如在提到环境变量时引用[1],或者在数据分析时提到pandas和matplotlib。 可能还需要考虑用户的实际操作中遇到的困难,比如认证流程复杂,或者异步爬取的高效性,所以需要给出清晰的步骤和代码示例,帮助用户一步步实现。 总结下来,回答的结构应该是: 1. 注册Twitter开发者账号 2. 选择工具和库(tweepy、requests、异步库) 3. 认证流程(API密钥获取,环境变量) 4. 数据爬取方法(两种示例:tweepy和requests) 5. 异步爬取示例 6. 数据存储与分析 7. 注意事项(遵守政策,速率限制) 8. 相关问题 同时,确保每个部分都有对应的代码示例和解释,引用标记在适当的位置,比如提到dotenv时添加[^1],提到数据分析工具时引用[1]和[^2]。</think>### 如何用Python爬取Twitter数据? 以下是分步指南,涵盖主流工具和方法(以Twitter API v2为例): --- #### 1. **注册Twitter开发者账号** - 访问 [Twitter开发者平台](https://developer.twitter.com/),申请“Elevated Access”权限(需审核)[^1] - 创建项目并获取API凭证:`API Key`、`API Secret Key`、`Bearer Token` --- #### 2. **选择工具与库** - **荐工具**: - `tweepy`:Twitter官方荐的Python库,简化API调用 - `requests` + `OAuth1`:直接通过HTTP请求交互 - `aiohttp` + `asyncio`:实现异步高效爬取[^1] - **数据存储与分析**: - 使用`pandas`存储为CSV或DataFrame - 用`matplotlib`或`seaborn`可视化分析[^1] --- #### 3. **认证流程** - **使用`tweepy`认证示例**: ```python import tweepy import os from dotenv import load_dotenv # 管理环境变量[^1] load_dotenv() client = tweepy.Client( bearer_token=os.getenv("BEARER_TOKEN"), consumer_key=os.getenv("API_KEY"), consumer_secret=os.getenv("API_SECRET") ) ``` --- #### 4. **数据爬取方法** - **方法1:通过`tweepy`获取用户** ```python def get_user_tweets(username, max_results=10): user = client.get_user(username=username) tweets = client.get_users_tweets( user.data.id, max_results=max_results, tweet_fields=["created_at", "public_metrics"] ) return tweets.data ``` - 返回字段包含发布时间、点赞数、转发数等 - **方法2:直接调用API(使用`requests`)** ```python import requests headers = {"Authorization": f"Bearer {BEARER_TOKEN}"} params = { "query": "Python lang:en -is:retweet", "max_results": 50, "tweet.fields": "created_at" } response = requests.get( "https://api.twitter.com/2/tweets/search/recent", headers=headers, params=params ) ``` --- #### 5. **异步爬取示例** ```python import aiohttp import asyncio async def fetch_tweets_async(url, headers, params): async with aiohttp.ClientSession() as session: async with session.get(url, headers=headers, params=params) as response: return await response.json() # 调用示例 async def main(): data = await fetch_tweets_async( "https://api.twitter.com/2/tweets/search/recent", headers, {"query": "#AI", "max_results": 100} ) print(data) ``` --- #### 6. **数据存储与分析** ```python import pandas as pd # 将数据转为DataFrame tweets = get_user_tweets("TwitterDev") df = pd.DataFrame([tweet.data for tweet in tweets]) # 保存为CSV df.to_csv("twitter_data.csv", index=False) # 分析点赞数分布 df["public_metrics.like_count"].hist() ``` --- #### 7. **注意事项** - 遵守[Twitter开发者协议](https://developer.twitter.com/en/docs/twitter-api),避免爬取隐私数据 - 免费API有速率限制(如450请求/15分钟) - 高级功能(历史数据、流式API)需付费订阅 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值