🚀 DAY 5 OF LAUNCH WEEK: Introducing Socket Firewall Enterprise.Learn more
Socket
Book a DemoInstallSign in
Socket

@daidaitw/twitter-scraper

Package Overview
Dependencies
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@daidaitw/twitter-scraper

A clean and powerful Twitter/X scraping library with CycleTLS support, proxy configuration, and full TypeScript type definitions | 简洁的 Twitter/X 爬虫库,支持 CycleTLS 和代理,提供完整的 TypeScript 类型定义

latest
Source
npmnpm
Version
1.0.6
Version published
Maintainers
1
Created
Source

Twitter Scraper

一个简洁、强大的 Twitter/X 数据爬虫库,支持 CycleTLS 和代理,提供完整的 TypeScript 类型定义。

A clean and powerful Twitter/X scraping library with CycleTLS support, proxy configuration, and full TypeScript type definitions.

✨ Features / 特性

  • 🚀 简洁易用 - 简单直观的 API 设计
  • 🔐 完整认证 - 支持用户登录和访客模式
  • 🌐 代理支持 - 内置代理配置支持
  • 🔒 TLS 指纹 - 可选 CycleTLS 支持,绕过反爬虫检测
  • 📝 TypeScript - 完整的类型定义
  • 🍪 Cookie 管理 - 灵活的 Cookie 存储和复用
  • 🎯 全功能 - 支持推文获取、搜索、用户信息等

📦 Installation / 安装

npm install @daidaitw/twitter-scraper

可选依赖(用于 TLS 指纹伪装):

npm install cycletls

🚀 Quick Start / 快速开始

基础用法

import { TwitterScraper } from '@daidaitw/twitter-scraper';

const scraper = new TwitterScraper(
  proxyUrl: "http://localhost:7890"
  );

// 登录
await scraper.login('your_username', 'your_password');



// 获取用户信息
const profile = await scraper.getUserProfile('elonmusk');
console.log(profile);
// 获取用户推文
const tweets = await scraper.getUserTweets(profile.id, 20);
console.log(tweets);
// 搜索推文
const searchResults = await scraper.searchTweets('AI', 50);
console.log(searchResults);

使用 CycleTLS(推荐用于生产环境)

import { TwitterScraper ,cycleTLSFetch} from '@daidaitw/twitter-scraper';cycletls-fetch.js';

const scraper = new TwitterScraper({
  fetch:cycleTLSFetch,
  proxyUrl: 'http://your-proxy:port'
});

await scraper.login('username', 'password');

使用已有 Cookies

import { TwitterScraper } from '@daidaitw/twitter-scraper';
import fs from 'fs';

const scraper = new TwitterScraper();

// 从文件加载 cookies
const cookies = JSON.parse(fs.readFileSync('cookies.json', 'utf-8'));
await scraper.setCookies(cookies);

// 验证登录状态
const isLoggedIn = await scraper.isLoggedIn();
console.log('Login status:', isLoggedIn);

📖 API Documentation / API 文档

TwitterScraper

主要的爬虫类,提供所有 Twitter 数据获取功能。

Constructor Options

interface ScraperOptions {
  useCycleTLS?: boolean;        // 使用 CycleTLS(默认:false)
  cycleTLSFetch?: Function;     // CycleTLS fetch 函数
  proxyUrl?: string;            // 代理 URL
  debug?: boolean;              // 调试模式(默认:false)
}

Methods

login(username, password, email?, twoFactorSecret?)

用户登录。

await scraper.login('username', 'password');
// 带邮箱验证
await scraper.login('username', 'password', 'email@example.com');
// 带两步验证
await scraper.login('username', 'password', null, 'YOUR_2FA_SECRET');
isLoggedIn()

检查登录状态。

const loggedIn = await scraper.isLoggedIn();
getCookies()

获取当前 cookies。

const cookies = await scraper.getCookies();
setCookies(cookies)

设置 cookies。

await scraper.setCookies(cookiesArray);
getUserProfile(username)

获取用户资料。

const profile = await scraper.getUserProfile('elonmusk');
console.log(profile.name, profile.followers_count);
getUserTweets(username, count?, cursor?)

获取用户推文。

// 获取用户信息
const profile = await scraper.getUserProfile('elonmusk');
console.log(profile);
// 获取 20 条推文
const tweets = await scraper.getUserTweets(profile.id, 20);
getTweetDetail(tweetId)

获取推文详情。

const tweet = await scraper.getTweetDetail('1234567890');
console.log(tweet.full_text, tweet.favorite_count);
searchTweets(query, count?, cursor?, searchMode?)

搜索推文。

// 基础搜索
const results = await scraper.searchTweets('AI technology', 50);

// 只看最新
const latest = await scraper.searchTweets('bitcoin', 20, null, 'Latest');

// 只看热门
const top = await scraper.searchTweets('ethereum', 20, null, 'Top');
likeTweet(tweetId)

点赞推文。

await scraper.likeTweet('1234567890');
unlikeTweet(tweetId)

取消点赞。

await scraper.unlikeTweet('1234567890');
retweet(tweetId)

转推。

await scraper.retweet('1234567890');
unretweet(tweetId)

取消转推。

await scraper.unretweet('1234567890');
followUser(userId)

关注用户。

await scraper.followUser('44196397'); // Elon Musk's user ID
unfollowUser(userId)

取消关注。

await scraper.unfollowUser('44196397');

🔧 Advanced Usage / 高级用法

import fs from 'fs';

const scraper = new TwitterScraper();
await scraper.login('username', 'password');

// 保存 cookies
const cookies = await scraper.getCookies();
fs.writeFileSync('cookies.json', JSON.stringify(cookies, null, 2));

// 下次直接使用 cookies
const savedCookies = JSON.parse(fs.readFileSync('cookies.json'));
await scraper.setCookies(savedCookies);

错误处理

try {
  await scraper.login('username', 'password');
} catch (error) {
  if (error.message.includes('Wrong password')) {
    console.error('密码错误');
  } else if (error.message.includes('rate limit')) {
    console.error('请求过于频繁');
  } else {
    console.error('登录失败:', error.message);
  }
}

批量操作

// 批量获取多个用户的推文
const usernames = ['elonmusk', 'BillGates', 'tim_cook'];
const allTweets = await Promise.all(
  usernames.map(username => scraper.getUserTweets(username, 10))
);

自定义 Fetch

import { createFetch } from '@daidaitw/twitter-scraper';

// 创建自定义 fetch 函数
const customFetch = createFetch({
  proxyUrl: 'http://localhost:7890',
  headers: {
    'User-Agent': 'Custom UA'
  }
});

const scraper = new TwitterScraper();
// 替换内部 fetch
scraper.auth.fetch = customFetch;

🛡️ Best Practices / 最佳实践

  • 使用代理 - 避免 IP 被封禁
  • Cookie 复用 - 减少登录次数
  • 控制频率 - 添加请求延迟
  • 错误重试 - 实现重试机制
  • CycleTLS - 生产环境推荐使用
// 示例:带重试和延迟的爬虫
class SafeScraper {
  constructor(options) {
    this.scraper = new TwitterScraper(options);
    this.delay = 2000; // 2秒延迟
  }

  async sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  async retryOperation(operation, maxRetries = 3) {
    for (let i = 0; i < maxRetries; i++) {
      try {
        return await operation();
      } catch (error) {
        if (i === maxRetries - 1) throw error;
        await this.sleep(this.delay * (i + 1));
      }
    }
  }

  async getUserTweets(username, count) {
    return this.retryOperation(async () => {
      const result = await this.scraper.getUserTweets(username, count);
      await this.sleep(this.delay);
      return result;
    });
  }
}

📝 Type Definitions / 类型定义

完整的 TypeScript 类型支持:

import type {
  Tweet,
  User,
  ScraperOptions
} from '@daidaitw/twitter-scraper';

const scraper: TwitterScraper = new TwitterScraper(options);
const tweets: Tweet[] = await scraper.getUserTweets('username', 20);
const user: User = await scraper.getUserProfile('username');

🤝 Contributing / 贡献

欢迎提交 Issue 和 Pull Request!

📄 License / 许可证

MIT License - 详见 LICENSE 文件

⚠️ Disclaimer / 免责声明

本项目仅供学习和研究使用。使用本工具时请遵守 Twitter 的服务条款和相关法律法规。 作者不对因使用本工具导致的任何问题负责。

This project is for educational and research purposes only. Please comply with Twitter's Terms of Service and relevant laws when using this tool. The author is not responsible for any issues arising from the use of this tool.

📚 Resources / 相关资源

Keywords

twitter

FAQs

Package last updated on 14 Oct 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts