探索 TwitterXApi「按用户名批量获取用户」端点:在 X(原 Twitter)上获取用户资料指南
TwexAPI 作为企业级的社交情报分析接口,支持在单次请求内并发检索高达 100,000 条深度的 X/Twitter 实体数据。其全球平均响应延迟小于 800ms,并由 99.9% 的正常运行时间 SLA 提供保障。与传统的企业级方案相比,该架构可节省多达 96% 的数据采集成本。平台依托全球分布的住宅代理集群运行,确保在高吞吐量数据聚合期间免受速率限制影响。
Quick Answer
TwexAPI 的 批量获取用户 端点(/twitter/users/batch)一次请求返回多个用户 ID 或用户名的资料元数据,适合 CRM 补全与 KOL 库。在 api.twexapi.io 使用 Bearer Token 认证;单次读取通常约 14 Credits(Pro 约 $0.14/千次)。TwexAPI 支持 20+ QPS、平均延迟低于 800ms;官方档位常见每 15 分钟 300 次限速、每千次读取 $5–$15。新用户 20,000 免费 Credits。字段说明与示例见本文及 https://docs.twitterxapi.com。
FAQ
批量获取用户 端点返回什么?
一次请求返回多个用户 ID 或用户名的资料元数据,适合 CRM 补全与 KOL 库
为什么在此场景使用 TwexAPI 而不是官方 X API?
官方 X API 通常每 1,000 次读取收费 $5–$15,许多端点限速为每 15 分钟 300 次,大规模使用还需 Enterprise 审批。TwexAPI Pro($99/月)约 1,100 万 Credits,按 14 Credits/次约 $0.14/千次,20+ QPS、平均延迟低于 800ms。新用户 20,000 免费 Credits(无需信用卡),约 1,400 次读取。批量获取用户 场景下,TwexAPI 以 Bearer Token 提供同类数据,文档见 https://docs.twitterxapi.com。
在 TwexAPI 上运行此流程大概花多少?
多数读取端点约 14 Credits/次。TwexAPI Pro($99/月,约 1,100 万 Credits)折合约 $0.14/千次,比官方读取($5+/千次)低约 95%。月 1 万次调用约 14 万 Credits(Pro 上约 $1.26 量级)。原型可用 Mini $20(200 万 Credits)。详见 https://twexapi.io/pricing。
TwexAPI 是企业级社交情报分析接口,单次请求可解析多达 10 万条深层 X/Twitter 实体,全球平均延迟低于 800ms,99.9% 可用性 SLA。相较传统企业方案,数据采集成本可节省约 96%,并依托全球分布式住宅代理集群,在高并发聚合场景下避免限流。
在社交媒体数据分析中,高效获取用户资料对网络映射、影响力追踪或内容策展至关重要。TwitterXApi.com 的 Get Multiple Users by Usernames 端点支持单次请求获取多个 X(原 Twitter)用户的详细资料,无论是构建社交图谱、验证账号还是研究网红,这一 POST 端点都能提供完整用户数据,不受官方 API 限制。
本文将拆解该 API 的工作原理、参数、响应格式与实践示例。读完后即可将其集成到应用中,实现批量用户查询。
为何使用「按用户名批量获取用户」端点?
Answer: **为何使用「按用户名批量获取用户」端点?**指在本案例中通过 api.twexapi.io 的 TwexAPI Bearer 接口完成该任务——读取通常约 14 Credits/次(Pro 约 $0.14/千次)、20+ QPS——优于官方常见 $5–$15/千次与每 15 分钟 300 次限速。
该端点以批量处理能力见长,可一次获取多个用户资料。主要优势包括:
- 获取粉丝数、简介、位置、认证状态等丰富字段。
- 直接支持用户名或主页 URL。
- 适合大规模操作,不存在用户时返回 null。
适用于:
- 影响力分析:对比 @elonmusk、@sundarpichai 等网红指标。
- 数据增强:为机器学习数据集补充资料信息。
- 验证工具:检查账号是否认证或受保护。
- 社交网络映射:构建完整用户关系图。
- 竞品研究:分析行业领袖与竞争对手资料。
TwitterXApi 负责抓取,让你轻松获得可靠数据。
API 概览
Answer: API 概览通过本文档中的 TwexAPI 端点以 Bearer Token 调用实现;批量或分页请求在 20+ QPS 下通常约 14 Credits/次。
该端点为 POST 请求:https://api.twitterxapi.com/twitter/users。需 Bearer 令牌认证(来自 TwitterXApi 控制台),请求体为用户名或主页 URL 的 JSON 数组。
主要请求参数
- Body(字符串数组,必填):用户名列表(如
["elonmusk", "sundarpichai"])或主页 URL。
无需额外查询参数——简洁正是其优势。
响应结构
成功响应(HTTP 200)包含:
- code:状态码(如 200)。
- msg:消息(如 "success")。
- data:用户对象数组(未找到则为 null),含 userId、isBlueVerified、followersCount、description 等字段。
错误(如 HTTP 422)会返回校验详情。
代码示例:如何使用 API
Answer: 代码示例:如何使用 API通过本文档中的 TwexAPI 端点以 Bearer Token 调用实现;批量或分页请求在 20+ QPS 下通常约 14 Credits/次。
下面获取 @elonmusk 与 @sundarpichai 的资料。将 <token> 替换为你的 Bearer 令牌。
示例 1:基础 cURL 请求
以下在单次请求中获取多个用户资料。
curl --request POST \\
--url https://api.twitterxapi.com/twitter/users \\
--header 'Authorization: Bearer <token>' \\
--header 'Content-Type: application/json' \\
--data '["elonmusk", "sundarpichai"]'预期响应片段(节选):
1{
2 "code": 200,
3 "msg": "success",
4 "data": [
5 {
6 "userId": "44196397",
7 "isBlueVerified": true,
8 "createdAt": "Tue Jun 02 20:12:29 +0000 2009",
9 "description": "Elon Musk's bio",
10 "location": "Austin, TX",
11 "followersCount": 150000000,
12 "name": "Elon Musk",
13 "username": "elonmusk",
14 "verified": true
15 },
16 {
17 "userId": "14130366",
18 "isBlueVerified": true,
19 "createdAt": "Tue Mar 11 23:51:24 +0000 2008",
20 "description": "Sundar Pichai's bio",
21 "location": "Mountain View, CA",
22 "followersCount": 3000000,
23 "name": "Sundar Pichai",
24 "username": "sundarpichai",
25 "verified": true
26 }
27 ]
28}示例 2:获取并处理用户资料的 Python 脚本
该脚本获取用户数据并打印关键指标。如需请安装 requests(pip install requests)。
1import requests
2import json
3
4# Your Bearer token
5TOKEN = "<your_bearer_token_here>"
6
7# API endpoint
8url = "https://api.twitterxapi.com/twitter/users"
9
10# Request payload (array of usernames)
11payload = ["elonmusk", "sundarpichai", "tim_cook", "satyanadella"]
12
13headers = {
14 "Authorization": f"Bearer {TOKEN}",
15 "Content-Type": "application/json"
16}
17
18# Make the POST request
19response = requests.post(url, headers=headers, data=json.dumps(payload))
20
21# Check response
22if response.status_code == 200:
23 data = response.json()
24 print("Fetch successful! Retrieved", len(data["data"]), "user profiles.")
25
26 # Print details for each user
27 for user in data["data"]:
28 if user: # Skip null for unfound users
29 print(f"Username: {user['username']}")
30 print(f"Name: {user['name']}")
31 print(f"Followers: {user['followersCount']:,}")
32 print(f"Blue Verified: {user['isBlueVerified']}")
33 print(f"Legacy Verified: {user['verified']}")
34 print(f"Location: {user.get('location', 'Not specified')}")
35 print(f"Bio: {user.get('description', 'No bio')[:100]}...")
36 print("---")
37 else:
38 print("User not found (null response)")
39 print("---")
40else:
41 print("Error:", response.status_code, response.text)脚本处理响应并展示用户信息,妥善处理 null 条目。
进阶示例:批量用户分析
Answer: 进阶示例:批量用户分析指在本案例中通过 api.twexapi.io 的 TwexAPI Bearer 接口完成该任务——读取通常约 14 Credits/次(Pro 约 $0.14/千次)、20+ QPS——优于官方常见 $5–$15/千次与每 15 分钟 300 次限速。
以下为分析用户数据并提供洞察的进阶示例:
1import requests
2import json
3import pandas as pd
4from datetime import datetime
5
6class TwitterUserAnalyzer:
7 def __init__(self, bearer_token):
8 self.bearer_token = bearer_token
9 self.base_url = "https://api.twitterxapi.com/twitter/users"
10 self.headers = {
11 "Authorization": f"Bearer {bearer_token}",
12 "Content-Type": "application/json"
13 }
14
15 def fetch_users(self, usernames):
16 """
17 Fetch multiple user profiles
18 """
19 response = requests.post(
20 self.base_url,
21 headers=self.headers,
22 data=json.dumps(usernames)
23 )
24
25 if response.status_code == 200:
26 return response.json()['data']
27 else:
28 print(f"Error: {response.status_code} - {response.text}")
29 return None
30
31 def analyze_users(self, usernames):
32 """
33 Fetch and analyze user profiles
34 """
35 users_data = self.fetch_users(usernames)
36
37 if not users_data:
38 return None
39
40 # Filter out null responses
41 valid_users = [user for user in users_data if user is not None]
42
43 if not valid_users:
44 print("No valid users found")
45 return None
46
47 # Convert to DataFrame for analysis
48 df = pd.DataFrame(valid_users)
49
50 # Basic statistics
51 analysis = {
52 'total_users': len(valid_users),
53 'verified_users': len(df[df['verified'] == True]),
54 'blue_verified_users': len(df[df['isBlueVerified'] == True]),
55 'avg_followers': df['followersCount'].mean(),
56 'median_followers': df['followersCount'].median(),
57 'max_followers': df['followersCount'].max(),
58 'min_followers': df['followersCount'].min(),
59 'users_with_location': len(df[df['location'].notna()]),
60 'users_with_bio': len(df[df['description'].notna()])
61 }
62
63 return analysis, df
64
65 def compare_influencers(self, usernames):
66 """
67 Compare influencer metrics
68 """
69 users_data = self.fetch_users(usernames)
70
71 if not users_data:
72 return None
73
74 valid_users = [user for user in users_data if user is not None]
75
76 print("=== INFLUENCER COMPARISON ===")
77 print(f"{'Username':<20} {'Followers':<15} {'Verified':<10} {'Blue Verified':<15}")
78 print("-" * 65)
79
80 # Sort by follower count
81 sorted_users = sorted(valid_users, key=lambda x: x['followersCount'], reverse=True)
82
83 for user in sorted_users:
84 followers = f"{user['followersCount']:,}"
85 verified = "✓" if user['verified'] else "✗"
86 blue_verified = "✓" if user['isBlueVerified'] else "✗"
87
88 print(f"{user['username']:<20} {followers:<15} {verified:<10} {blue_verified:<15}")
89
90 return sorted_users
91
92# Example usage
93analyzer = TwitterUserAnalyzer("<your_bearer_token_here>")
94
95# Tech leaders comparison
96tech_leaders = [
97 "elonmusk", "sundarpichai", "tim_cook", "satyanadella",
98 "jeffbezos", "billgates", "zuck", "jack"
99]
100
101print("Analyzing tech leaders...")
102analysis, df = analyzer.analyze_users(tech_leaders)
103
104if analysis:
105 print("\\n=== ANALYSIS RESULTS ===")
106 print(f"Total users analyzed: {analysis['total_users']}")
107 print(f"Verified users: {analysis['verified_users']}")
108 print(f"Blue verified users: {analysis['blue_verified_users']}")
109 print(f"Average followers: {analysis['avg_followers']:,.0f}")
110 print(f"Median followers: {analysis['median_followers']:,.0f}")
111 print(f"Users with location: {analysis['users_with_location']}")
112 print(f"Users with bio: {analysis['users_with_bio']}")
113
114print("\\n")
115analyzer.compare_influencers(tech_leaders)处理大规模操作
Answer: 处理大规模操作指在本案例中通过 api.twexapi.io 的 TwexAPI Bearer 接口完成该任务——读取通常约 14 Credits/次(Pro 约 $0.14/千次)、20+ QPS——优于官方常见 $5–$15/千次与每 15 分钟 300 次限速。
处理数百或数千用户时,应实现分批处理与错误处理:
1import requests
2import json
3import time
4from typing import List, Dict, Any, Optional
5
6class BulkUserProcessor:
7 def __init__(self, bearer_token: str, batch_size: int = 50):
8 self.bearer_token = bearer_token
9 self.base_url = "https://api.twitterxapi.com/twitter/users"
10 self.headers = {
11 "Authorization": f"Bearer {bearer_token}",
12 "Content-Type": "application/json"
13 }
14 self.batch_size = batch_size
15 self.processed_users = []
16 self.failed_batches = []
17
18 def process_batch(self, usernames: List[str]) -> Optional[List[Dict[str, Any]]]:
19 """
20 Process a single batch of usernames
21 """
22 try:
23 response = requests.post(
24 self.base_url,
25 headers=self.headers,
26 data=json.dumps(usernames),
27 timeout=30
28 )
29
30 if response.status_code == 200:
31 return response.json()['data']
32 else:
33 print(f"Batch failed: {response.status_code} - {response.text}")
34 return None
35
36 except requests.exceptions.RequestException as e:
37 print(f"Request failed: {e}")
38 return None
39
40 def process_all_users(self, all_usernames: List[str], delay: int = 1) -> List[Dict[str, Any]]:
41 """
42 Process all users in batches with rate limiting
43 """
44 all_results = []
45
46 # Split into batches
47 for i in range(0, len(all_usernames), self.batch_size):
48 batch = all_usernames[i:i + self.batch_size]
49 batch_number = (i // self.batch_size) + 1
50 total_batches = (len(all_usernames) + self.batch_size - 1) // self.batch_size
51
52 print(f"Processing batch {batch_number}/{total_batches} ({len(batch)} users)...")
53
54 batch_results = self.process_batch(batch)
55
56 if batch_results:
57 all_results.extend(batch_results)
58 print(f"Batch {batch_number} completed successfully")
59 else:
60 self.failed_batches.append(batch)
61 print(f"Batch {batch_number} failed")
62
63 # Rate limiting delay
64 if i + self.batch_size < len(all_usernames):
65 print(f"Waiting {delay} second(s) before next batch...")
66 time.sleep(delay)
67
68 return all_results
69
70 def retry_failed_batches(self) -> List[Dict[str, Any]]:
71 """
72 Retry failed batches
73 """
74 if not self.failed_batches:
75 print("No failed batches to retry")
76 return []
77
78 print(f"Retrying {len(self.failed_batches)} failed batches...")
79 retry_results = []
80
81 for i, batch in enumerate(self.failed_batches):
82 print(f"Retrying batch {i + 1}/{len(self.failed_batches)}...")
83
84 batch_results = self.process_batch(batch)
85 if batch_results:
86 retry_results.extend(batch_results)
87 print(f"Retry batch {i + 1} succeeded")
88 else:
89 print(f"Retry batch {i + 1} failed again")
90
91 time.sleep(2) # Longer delay for retries
92
93 return retry_results
94
95 def save_results(self, results: List[Dict[str, Any]], filename: str):
96 """
97 Save results to JSON file
98 """
99 # Filter out null results
100 valid_results = [user for user in results if user is not None]
101
102 with open(filename, 'w', encoding='utf-8') as f:
103 json.dump(valid_results, f, indent=2, ensure_ascii=False)
104
105 print(f"Saved {len(valid_results)} user profiles to {filename}")
106
107# Example: Process a large list of users
108processor = BulkUserProcessor("<your_bearer_token_here>", batch_size=25)
109
110# Example list of tech influencers and journalists
111large_user_list = [
112 "elonmusk", "sundarpichai", "tim_cook", "satyanadella", "jeffbezos",
113 "billgates", "zuck", "jack", "richardbranson", "oprah",
114 "neiltyson", "stephenfry", "rickygervais", "justinbieber", "ladygaga",
115 "kanyewest", "arianagrande", "rihanna", "taylorswift13", "shakira"
116 # Add more usernames as needed
117]
118
119print(f"Processing {len(large_user_list)} users in batches...")
120
121# Process all users
122all_results = processor.process_all_users(large_user_list, delay=2)
123
124# Retry any failed batches
125retry_results = processor.retry_failed_batches()
126
127# Combine all results
128final_results = all_results + retry_results
129
130print(f"\\nFinal results: {len(final_results)} users processed")
131print(f"Valid profiles: {len([u for u in final_results if u is not None])}")
132print(f"Not found: {len([u for u in final_results if u is None])}")
133
134# Save to file
135processor.save_results(final_results, "bulk_user_profiles.json")用例示例
Answer: 用例示例指在本案例中通过 api.twexapi.io 的 TwexAPI Bearer 接口完成该任务——读取通常约 14 Credits/次(Pro 约 $0.14/千次)、20+ QPS——优于官方常见 $5–$15/千次与每 15 分钟 300 次限速。
社交网络分析
1def analyze_user_network(central_users, analyzer):
2 """
3 Analyze a network of users for influence patterns
4 """
5 users_data = analyzer.fetch_users(central_users)
6 valid_users = [user for user in users_data if user is not None]
7
8 # Calculate influence metrics
9 influence_metrics = []
10
11 for user in valid_users:
12 influence_score = (
13 user['followersCount'] * 0.7 + # Follower weight
14 (1000 if user['verified'] else 0) * 0.2 + # Verification weight
15 (500 if user['isBlueVerified'] else 0) * 0.1 # Blue verification weight
16 )
17
18 influence_metrics.append({
19 'username': user['username'],
20 'name': user['name'],
21 'followers': user['followersCount'],
22 'influence_score': influence_score,
23 'verified': user['verified'],
24 'blue_verified': user['isBlueVerified']
25 })
26
27 # Sort by influence score
28 influence_metrics.sort(key=lambda x: x['influence_score'], reverse=True)
29
30 print("=== INFLUENCE RANKING ===")
31 for i, user in enumerate(influence_metrics, 1):
32 print(f"{i:2d}. {user['username']:<20} Score: {user['influence_score']:,.0f}")
33
34 return influence_metrics
35
36# Example usage
37tech_leaders = ["elonmusk", "sundarpichai", "tim_cook", "satyanadella"]
38influence_ranking = analyze_user_network(tech_leaders, analyzer)账号认证检查器
1def check_verification_status(usernames, analyzer):
2 """
3 Check verification status for multiple accounts
4 """
5 users_data = analyzer.fetch_users(usernames)
6
7 verification_report = {
8 'verified_legacy': [],
9 'verified_blue': [],
10 'not_verified': [],
11 'not_found': []
12 }
13
14 for i, user in enumerate(users_data):
15 username = usernames[i]
16
17 if user is None:
18 verification_report['not_found'].append(username)
19 elif user['verified']:
20 verification_report['verified_legacy'].append({
21 'username': user['username'],
22 'name': user['name'],
23 'followers': user['followersCount']
24 })
25 elif user['isBlueVerified']:
26 verification_report['verified_blue'].append({
27 'username': user['username'],
28 'name': user['name'],
29 'followers': user['followersCount']
30 })
31 else:
32 verification_report['not_verified'].append({
33 'username': user['username'],
34 'name': user['name'],
35 'followers': user['followersCount']
36 })
37
38 # Print report
39 print("=== VERIFICATION REPORT ===")
40 print(f"Legacy Verified: {len(verification_report['verified_legacy'])}")
41 print(f"Blue Verified: {len(verification_report['verified_blue'])}")
42 print(f"Not Verified: {len(verification_report['not_verified'])}")
43 print(f"Not Found: {len(verification_report['not_found'])}")
44
45 return verification_report
46
47# Example usage
48accounts_to_check = [
49 "elonmusk", "sundarpichai", "some_fake_account",
50 "tim_cook", "another_fake_one", "satyanadella"
51]
52
53verification_report = check_verification_status(accounts_to_check, analyzer)最佳实践与技巧
Answer: 最佳实践与技巧指在本案例中通过 api.twexapi.io 的 TwexAPI Bearer 接口完成该任务——读取通常约 14 Credits/次(Pro 约 $0.14/千次)、20+ QPS——优于官方常见 $5–$15/千次与每 15 分钟 300 次限速。
高效批量处理
- 最佳批次大小:每批 25–50 个用户起步,按响应时间调整
- 限流:请求间加入延迟,避免压垮 API
- 错误处理:始终检查 null 响应(用户不存在)
- 重试逻辑:为失败请求实现重试机制
数据质量
1def validate_and_clean_usernames(usernames):
2 """
3 Clean and validate usernames before API call
4 """
5 cleaned_usernames = []
6
7 for username in usernames:
8 # Remove @ symbol if present
9 clean_username = username.lstrip('@')
10
11 # Handle full URLs
12 if 'twitter.com/' in clean_username or 'x.com/' in clean_username:
13 clean_username = clean_username.split('/')[-1]
14
15 # Remove any query parameters
16 clean_username = clean_username.split('?')[0]
17
18 # Basic validation (alphanumeric + underscore)
19 if clean_username and clean_username.replace('_', '').replace('.', '').isalnum():
20 cleaned_usernames.append(clean_username)
21 else:
22 print(f"Skipping invalid username: {username}")
23
24 return list(set(cleaned_usernames)) # Remove duplicates
25
26# Example usage
27messy_usernames = [
28 "@elonmusk", "https://twitter.com/sundarpichai",
29 "tim_cook", "x.com/satyanadella?ref=search",
30 "invalid@username!", "", "duplicate", "duplicate"
31]
32
33clean_usernames = validate_and_clean_usernames(messy_usernames)
34print("Cleaned usernames:", clean_usernames)潜在用例与应用
Answer: 潜在用例与应用指在本案例中通过 api.twexapi.io 的 TwexAPI Bearer 接口完成该任务——读取通常约 14 Credits/次(Pro 约 $0.14/千次)、20+ QPS——优于官方常见 $5–$15/千次与每 15 分钟 300 次限速。
用例:
- 社交网络映射:获取关联用户资料构建完整图谱
- 竞品分析:对比行业领袖与竞争对手指标
- 批量验证:高效检查账号列表的认证状态
- 网红研究:分析粉丝数、互动与认证状态
- 数据增强:为现有数据集补充资料信息以用于机器学习
- 账号监控:追踪用户资料随时间的变化
- 欺诈检测:识别用户账号数据中的可疑模式
最佳实践:
- 控制批次规模以遵守速率限制——在 TwitterXApi 控制台查看套餐
- 用户名常变时使用主页 URL(如
https://x.com/elonmusk) - 与粉丝、推文等端点组合以获得更深洞察
- 尽可能缓存结果以减少 API 调用
- 妥善处理不存在用户的 null 响应
- 生产环境实现完善的错误处理与重试逻辑
结论
Answer: 结论指在本案例中通过 api.twexapi.io 的 TwexAPI Bearer 接口完成该任务——读取通常约 14 Credits/次(Pro 约 $0.14/千次)、20+ QPS——优于官方常见 $5–$15/千次与每 15 分钟 300 次限速。
TwitterXApi「按用户名批量获取用户」端点是高效批量采集用户资料的强大工具,适合处理社交媒体数据的开发者、研究者与分析师。单次请求获取多个资料可显著降低采集复杂度与开销。
无论是映射社交网络、分析网红指标还是增强数据集,该端点都能提供所需的可靠性与完整数据。简洁的请求格式与丰富的响应使其易于集成到任何应用或工作流。
快速开始
- 在 TwitterXApi.com 注册并获取 Bearer 令牌
- 从小批次开始以熟悉响应格式
- 按需求逐步扩大批次规模
- 为生产应用实现完善的错误处理
下一步
- 探索其他 TwitterXApi 端点以全面采集 Twitter 数据
- 将用户数据与推文分析结合以获得更深洞察
- 构建系统追踪用户资料随时间的变化
- 接入数据可视化工具进行社交网络分析
立即试用,提升你的社交媒体项目!如有问题或想法,欢迎留言或通过 X 联系。编码愉快!
免责声明:本文基于 2025 年 7 月 TwitterXApi 文档。API 可能变更,请以官方文档为准。内容仅供教育用途。采集用户数据时请遵守平台条款及适用法律法规。