Added tweets from nine users
Browse files- 03Added/Added_user_tweets.db +3 -0
- 03Added/requirements.txt +3 -0
- 03Added/spi06-4-2.py +393 -0
- 03Added/users.txt +1 -0
03Added/Added_user_tweets.db
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b681719a2d916379bcfcd376250c3d349f6e07e02f36f7e3b27fdc170ff34056
|
| 3 |
+
size 2224128
|
03Added/requirements.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
aiohttp>=3.8.0
|
| 2 |
+
pandas>=1.5.0
|
| 3 |
+
python-dateutil>=2.8.0
|
03Added/spi06-4-2.py
ADDED
|
@@ -0,0 +1,393 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import aiohttp
|
| 2 |
+
import asyncio
|
| 3 |
+
import json
|
| 4 |
+
import logging
|
| 5 |
+
import sqlite3
|
| 6 |
+
from datetime import datetime, timedelta
|
| 7 |
+
from email.utils import parsedate_to_datetime
|
| 8 |
+
from typing import List, Dict, Set
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
class QuotaLowException(Exception):
|
| 12 |
+
pass
|
| 13 |
+
|
| 14 |
+
class UserTweetsCrawler:
|
| 15 |
+
def __init__(self, api_key: str, users_file: str, output_db: str = "user_tweets.db"):
|
| 16 |
+
self.api_key = api_key
|
| 17 |
+
self.base_url = "https://api.tweetscout.io/v2"
|
| 18 |
+
self.users_file = users_file
|
| 19 |
+
self.db_path = output_db
|
| 20 |
+
self.headers = {
|
| 21 |
+
"ApiKey": api_key,
|
| 22 |
+
"Accept": "application/json"
|
| 23 |
+
}
|
| 24 |
+
self.processed_users_file = "processed_users.json"
|
| 25 |
+
self.no_tweets_users_file = "no_tweets_users.json"
|
| 26 |
+
self.processed_users: Set[str] = self._load_processed_users()
|
| 27 |
+
self.no_tweets_users: Set[str] = self._load_no_tweets_users()
|
| 28 |
+
self.api_call_count = 0
|
| 29 |
+
self.warning_threshold = 5500
|
| 30 |
+
self.last_save_time = datetime.now()
|
| 31 |
+
self.save_interval = timedelta(minutes=5)
|
| 32 |
+
self._setup_logging()
|
| 33 |
+
self._init_database()
|
| 34 |
+
|
| 35 |
+
def _load_processed_users(self) -> Set[str]:
|
| 36 |
+
if Path(self.processed_users_file).exists():
|
| 37 |
+
try:
|
| 38 |
+
with open(self.processed_users_file, 'r') as f:
|
| 39 |
+
return set(json.load(f))
|
| 40 |
+
except Exception as e:
|
| 41 |
+
logging.error(f"Error loading processed users: {e}")
|
| 42 |
+
return set()
|
| 43 |
+
return set()
|
| 44 |
+
|
| 45 |
+
def _load_no_tweets_users(self) -> Set[str]:
|
| 46 |
+
if Path(self.no_tweets_users_file).exists():
|
| 47 |
+
try:
|
| 48 |
+
with open(self.no_tweets_users_file, 'r') as f:
|
| 49 |
+
return set(json.load(f))
|
| 50 |
+
except Exception as e:
|
| 51 |
+
logging.error(f"Error loading no tweets users: {e}")
|
| 52 |
+
return set()
|
| 53 |
+
return set()
|
| 54 |
+
|
| 55 |
+
def _save_processed_users(self):
|
| 56 |
+
try:
|
| 57 |
+
with open(self.processed_users_file, 'w') as f:
|
| 58 |
+
json.dump(list(self.processed_users), f)
|
| 59 |
+
except Exception as e:
|
| 60 |
+
logging.error(f"Error saving processed users: {e}")
|
| 61 |
+
|
| 62 |
+
def _save_no_tweets_users(self):
|
| 63 |
+
try:
|
| 64 |
+
with open(self.no_tweets_users_file, 'w') as f:
|
| 65 |
+
json.dump(list(self.no_tweets_users), f)
|
| 66 |
+
except Exception as e:
|
| 67 |
+
logging.error(f"Error saving no tweets users: {e}")
|
| 68 |
+
|
| 69 |
+
def _setup_logging(self):
|
| 70 |
+
self.logger = logging.getLogger("UserTweetsCrawler")
|
| 71 |
+
self.logger.setLevel(logging.INFO)
|
| 72 |
+
|
| 73 |
+
console_handler = logging.StreamHandler()
|
| 74 |
+
console_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
|
| 75 |
+
self.logger.addHandler(console_handler)
|
| 76 |
+
|
| 77 |
+
file_handler = logging.FileHandler(f"crawler_{datetime.now().strftime('%Y%m%d_%H%M')}.log", encoding='utf-8')
|
| 78 |
+
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
|
| 79 |
+
self.logger.addHandler(file_handler)
|
| 80 |
+
|
| 81 |
+
def _init_database(self):
|
| 82 |
+
self.conn = sqlite3.connect(
|
| 83 |
+
self.db_path,
|
| 84 |
+
detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES,
|
| 85 |
+
timeout=30
|
| 86 |
+
)
|
| 87 |
+
self.conn.execute("PRAGMA journal_mode=WAL")
|
| 88 |
+
self.conn.execute("PRAGMA synchronous=NORMAL")
|
| 89 |
+
self.cursor = self.conn.cursor()
|
| 90 |
+
|
| 91 |
+
self.cursor.executescript('''
|
| 92 |
+
CREATE TABLE IF NOT EXISTS tweets (
|
| 93 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 94 |
+
tweet_id TEXT UNIQUE,
|
| 95 |
+
author_id TEXT,
|
| 96 |
+
author_name TEXT,
|
| 97 |
+
full_text TEXT,
|
| 98 |
+
created_at TIMESTAMP,
|
| 99 |
+
likes_count INTEGER DEFAULT 0,
|
| 100 |
+
retweets_count INTEGER DEFAULT 0,
|
| 101 |
+
replies_count INTEGER DEFAULT 0,
|
| 102 |
+
views_count INTEGER DEFAULT 0,
|
| 103 |
+
quote_count INTEGER DEFAULT 0,
|
| 104 |
+
is_quote_status BOOLEAN DEFAULT 0,
|
| 105 |
+
conversation_id TEXT,
|
| 106 |
+
in_reply_to_status_id TEXT,
|
| 107 |
+
quoted_status TEXT,
|
| 108 |
+
retweeted_status TEXT,
|
| 109 |
+
entities TEXT,
|
| 110 |
+
author_avatar TEXT,
|
| 111 |
+
author_description TEXT,
|
| 112 |
+
author_followers_count INT,
|
| 113 |
+
author_friends_count INT,
|
| 114 |
+
collected_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
| 115 |
+
);
|
| 116 |
+
|
| 117 |
+
CREATE INDEX IF NOT EXISTS idx_tweet_author ON tweets(author_id);
|
| 118 |
+
CREATE INDEX IF NOT EXISTS idx_tweet_id ON tweets(tweet_id);
|
| 119 |
+
CREATE INDEX IF NOT EXISTS idx_tweet_created ON tweets(created_at);
|
| 120 |
+
''')
|
| 121 |
+
self.conn.commit()
|
| 122 |
+
|
| 123 |
+
def load_users(self) -> List[Dict]:
|
| 124 |
+
try:
|
| 125 |
+
with open(self.users_file, 'r', encoding='utf-8') as f:
|
| 126 |
+
screen_names = [name.strip() for name in f.read().split(',')]
|
| 127 |
+
|
| 128 |
+
users = []
|
| 129 |
+
for screen_name in screen_names:
|
| 130 |
+
if screen_name and screen_name not in self.processed_users and screen_name not in self.no_tweets_users:
|
| 131 |
+
users.append({
|
| 132 |
+
'screen_name': screen_name,
|
| 133 |
+
'name': screen_name # 用于日志显示
|
| 134 |
+
})
|
| 135 |
+
|
| 136 |
+
self.logger.info(f"Loaded {len(users)} users to process")
|
| 137 |
+
return users
|
| 138 |
+
except Exception as e:
|
| 139 |
+
self.logger.error(f"Error loading users from file: {e}")
|
| 140 |
+
return []
|
| 141 |
+
|
| 142 |
+
async def check_api_quota(self) -> bool:
|
| 143 |
+
try:
|
| 144 |
+
async with aiohttp.ClientSession() as session:
|
| 145 |
+
async with session.get(f"{self.base_url}/quota", headers=self.headers) as response:
|
| 146 |
+
if response.status == 200:
|
| 147 |
+
quota_data = await response.json()
|
| 148 |
+
remaining = quota_data.get('remaining', 0)
|
| 149 |
+
self.logger.info(f"Current API quota remaining: {remaining}")
|
| 150 |
+
return remaining >= 100
|
| 151 |
+
except Exception as e:
|
| 152 |
+
self.logger.error(f"Error checking API quota: {e}")
|
| 153 |
+
return False
|
| 154 |
+
return True
|
| 155 |
+
|
| 156 |
+
async def get_user_id(self, screen_name: str) -> str:
|
| 157 |
+
try:
|
| 158 |
+
url = f"{self.base_url}/handle-to-id/{screen_name}"
|
| 159 |
+
async with aiohttp.ClientSession() as session:
|
| 160 |
+
async with session.get(url, headers=self.headers, timeout=30) as response:
|
| 161 |
+
self.logger.info(f"Attempting to get user ID for {screen_name}")
|
| 162 |
+
if response.status == 200:
|
| 163 |
+
data = await response.json()
|
| 164 |
+
user_id = data.get('id')
|
| 165 |
+
self.logger.info(f"Successfully got user ID for {screen_name}: {user_id}")
|
| 166 |
+
return user_id
|
| 167 |
+
else:
|
| 168 |
+
self.logger.error(f"Failed to get user ID for {screen_name}: Status {response.status}")
|
| 169 |
+
return None
|
| 170 |
+
except asyncio.TimeoutError:
|
| 171 |
+
self.logger.error(f"Timeout while getting user ID for {screen_name}")
|
| 172 |
+
return None
|
| 173 |
+
except Exception as e:
|
| 174 |
+
self.logger.error(f"Error getting user ID for {screen_name}: {e}")
|
| 175 |
+
return None
|
| 176 |
+
|
| 177 |
+
async def get_user_tweets(self, user: Dict, max_tweets: int = 100) -> List[Dict]:
|
| 178 |
+
try:
|
| 179 |
+
url = f"{self.base_url}/user-tweets"
|
| 180 |
+
all_tweets = []
|
| 181 |
+
cursor = ""
|
| 182 |
+
retries = 3
|
| 183 |
+
|
| 184 |
+
# 先获取用户ID
|
| 185 |
+
user_id = await self.get_user_id(user['screen_name'])
|
| 186 |
+
if not user_id:
|
| 187 |
+
self.logger.error(f"Could not get user ID for {user['screen_name']}")
|
| 188 |
+
return []
|
| 189 |
+
|
| 190 |
+
user['user_id'] = user_id
|
| 191 |
+
|
| 192 |
+
while len(all_tweets) < max_tweets:
|
| 193 |
+
if self.api_call_count >= self.warning_threshold:
|
| 194 |
+
if not await self.check_api_quota():
|
| 195 |
+
raise QuotaLowException("API quota running low")
|
| 196 |
+
|
| 197 |
+
data = {
|
| 198 |
+
"user_id": user_id,
|
| 199 |
+
"cursor": cursor
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
got_response = False
|
| 203 |
+
for attempt in range(retries):
|
| 204 |
+
try:
|
| 205 |
+
async with aiohttp.ClientSession() as session:
|
| 206 |
+
async with session.post(url, headers=self.headers, json=data, timeout=30) as response:
|
| 207 |
+
if response.status == 200:
|
| 208 |
+
got_response = True
|
| 209 |
+
self.api_call_count += 1
|
| 210 |
+
response_data = await response.json()
|
| 211 |
+
tweets = response_data.get('tweets', [])
|
| 212 |
+
|
| 213 |
+
if not tweets:
|
| 214 |
+
return all_tweets
|
| 215 |
+
|
| 216 |
+
all_tweets.extend(tweets)
|
| 217 |
+
|
| 218 |
+
cursor = response_data.get('next_cursor')
|
| 219 |
+
if not cursor or len(all_tweets) >= max_tweets:
|
| 220 |
+
return all_tweets[:max_tweets]
|
| 221 |
+
|
| 222 |
+
break
|
| 223 |
+
|
| 224 |
+
elif response.status == 429:
|
| 225 |
+
wait_time = int(response.headers.get('Retry-After', 60))
|
| 226 |
+
self.logger.warning(f"Rate limited, waiting {wait_time} seconds")
|
| 227 |
+
await asyncio.sleep(wait_time)
|
| 228 |
+
else:
|
| 229 |
+
self.logger.error(f"Failed to get tweets: Status {response.status}")
|
| 230 |
+
if attempt == retries - 1:
|
| 231 |
+
return all_tweets if got_response else []
|
| 232 |
+
except Exception as e:
|
| 233 |
+
self.logger.error(f"Request error: {str(e)}")
|
| 234 |
+
if attempt == retries - 1:
|
| 235 |
+
return all_tweets if got_response else []
|
| 236 |
+
await asyncio.sleep(5)
|
| 237 |
+
|
| 238 |
+
await asyncio.sleep(3)
|
| 239 |
+
|
| 240 |
+
return all_tweets
|
| 241 |
+
|
| 242 |
+
except QuotaLowException:
|
| 243 |
+
raise
|
| 244 |
+
except Exception as e:
|
| 245 |
+
self.logger.error(f"Error getting tweets: {str(e)}")
|
| 246 |
+
return []
|
| 247 |
+
|
| 248 |
+
def save_tweet(self, user: Dict, tweet_data: Dict) -> bool:
|
| 249 |
+
try:
|
| 250 |
+
created_at = parsedate_to_datetime(tweet_data.get('created_at'))
|
| 251 |
+
user_info = tweet_data.get('user', {})
|
| 252 |
+
quoted_status = tweet_data.get('quoted_status')
|
| 253 |
+
retweeted_status = tweet_data.get('retweeted_status')
|
| 254 |
+
|
| 255 |
+
self.cursor.execute('''
|
| 256 |
+
INSERT OR REPLACE INTO tweets
|
| 257 |
+
(tweet_id, author_id, author_name, full_text, created_at,
|
| 258 |
+
likes_count, retweets_count, replies_count, views_count,
|
| 259 |
+
quote_count, is_quote_status, conversation_id, in_reply_to_status_id,
|
| 260 |
+
quoted_status, retweeted_status, entities,
|
| 261 |
+
author_avatar, author_description, author_followers_count,
|
| 262 |
+
author_friends_count, collected_at)
|
| 263 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
|
| 264 |
+
''', (
|
| 265 |
+
tweet_data.get('id_str'),
|
| 266 |
+
user['user_id'],
|
| 267 |
+
user['screen_name'],
|
| 268 |
+
tweet_data.get('full_text', ''),
|
| 269 |
+
created_at,
|
| 270 |
+
tweet_data.get('favorite_count', 0),
|
| 271 |
+
tweet_data.get('retweet_count', 0),
|
| 272 |
+
tweet_data.get('reply_count', 0),
|
| 273 |
+
tweet_data.get('view_count', 0),
|
| 274 |
+
tweet_data.get('quote_count', 0),
|
| 275 |
+
tweet_data.get('is_quote_status', False),
|
| 276 |
+
tweet_data.get('conversation_id_str'),
|
| 277 |
+
tweet_data.get('in_reply_to_status_id_str'),
|
| 278 |
+
json.dumps(quoted_status) if quoted_status else None,
|
| 279 |
+
json.dumps(retweeted_status) if retweeted_status else None,
|
| 280 |
+
json.dumps(tweet_data.get('entities', {})),
|
| 281 |
+
user_info.get('avatar'),
|
| 282 |
+
user_info.get('description'),
|
| 283 |
+
user_info.get('followers_count'),
|
| 284 |
+
user_info.get('friends_count')
|
| 285 |
+
))
|
| 286 |
+
self.conn.commit()
|
| 287 |
+
return True
|
| 288 |
+
except Exception as e:
|
| 289 |
+
self.logger.error(f"Error saving tweet: {str(e)}")
|
| 290 |
+
self.conn.rollback()
|
| 291 |
+
return False
|
| 292 |
+
|
| 293 |
+
async def process_user(self, user: Dict):
|
| 294 |
+
try:
|
| 295 |
+
self.logger.info(f"Starting to process user {user['screen_name']}")
|
| 296 |
+
|
| 297 |
+
if datetime.now() - self.last_save_time > self.save_interval:
|
| 298 |
+
self._save_processed_users()
|
| 299 |
+
self._save_no_tweets_users()
|
| 300 |
+
self.last_save_time = datetime.now()
|
| 301 |
+
|
| 302 |
+
# 获取用户ID
|
| 303 |
+
self.logger.info(f"Getting user ID for {user['screen_name']}")
|
| 304 |
+
user_id = await self.get_user_id(user['screen_name'])
|
| 305 |
+
if not user_id:
|
| 306 |
+
self.logger.error(f"Failed to get user ID for {user['screen_name']}, skipping")
|
| 307 |
+
return
|
| 308 |
+
|
| 309 |
+
user['user_id'] = user_id
|
| 310 |
+
self.logger.info(f"Successfully got user ID {user_id} for {user['screen_name']}")
|
| 311 |
+
|
| 312 |
+
tweets = await self.get_user_tweets(user, max_tweets=100)
|
| 313 |
+
|
| 314 |
+
if not tweets:
|
| 315 |
+
self.logger.info(f"No tweets found for user {user['screen_name']}")
|
| 316 |
+
self.no_tweets_users.add(user['screen_name'])
|
| 317 |
+
self._save_no_tweets_users()
|
| 318 |
+
return
|
| 319 |
+
|
| 320 |
+
self.logger.info(f"Processing {len(tweets)} tweets for user {user['screen_name']}")
|
| 321 |
+
|
| 322 |
+
success = True
|
| 323 |
+
for i, tweet in enumerate(tweets, 1):
|
| 324 |
+
if i % 10 == 0:
|
| 325 |
+
self.logger.info(f"Processed {i}/{len(tweets)} tweets for {user['screen_name']}")
|
| 326 |
+
if not self.save_tweet(user, tweet):
|
| 327 |
+
success = False
|
| 328 |
+
break
|
| 329 |
+
|
| 330 |
+
if success:
|
| 331 |
+
self.processed_users.add(user['screen_name'])
|
| 332 |
+
self._save_processed_users()
|
| 333 |
+
self.logger.info(f"Successfully processed user {user['screen_name']}")
|
| 334 |
+
|
| 335 |
+
except QuotaLowException:
|
| 336 |
+
raise
|
| 337 |
+
except Exception as e:
|
| 338 |
+
self.logger.error(f"Error processing user {user['screen_name']}: {str(e)}")
|
| 339 |
+
import traceback
|
| 340 |
+
self.logger.error(traceback.format_exc())
|
| 341 |
+
|
| 342 |
+
async def run(self):
|
| 343 |
+
try:
|
| 344 |
+
users = self.load_users()
|
| 345 |
+
if not users:
|
| 346 |
+
self.logger.info("No users to process")
|
| 347 |
+
return
|
| 348 |
+
|
| 349 |
+
for user in users:
|
| 350 |
+
try:
|
| 351 |
+
await self.process_user(user)
|
| 352 |
+
except QuotaLowException:
|
| 353 |
+
self.logger.info(f"API quota running low, stopping at user {user['screen_name']}")
|
| 354 |
+
return
|
| 355 |
+
|
| 356 |
+
await asyncio.sleep(2)
|
| 357 |
+
|
| 358 |
+
except Exception as e:
|
| 359 |
+
self.logger.error(f"Unexpected error in main loop: {str(e)}")
|
| 360 |
+
raise
|
| 361 |
+
finally:
|
| 362 |
+
try:
|
| 363 |
+
self._save_processed_users()
|
| 364 |
+
self._save_no_tweets_users()
|
| 365 |
+
self.conn.close()
|
| 366 |
+
except Exception as e:
|
| 367 |
+
self.logger.error(f"Error during cleanup: {str(e)}")
|
| 368 |
+
|
| 369 |
+
async def main():
|
| 370 |
+
crawler = None
|
| 371 |
+
try:
|
| 372 |
+
crawler = UserTweetsCrawler(
|
| 373 |
+
api_key="aa6e0836-6bef-426e-8abb-db8dde0d0f68",
|
| 374 |
+
users_file="users.txt",
|
| 375 |
+
output_db="Added_user_tweets.db"
|
| 376 |
+
)
|
| 377 |
+
print("Crawler initialized, starting process...")
|
| 378 |
+
await crawler.run()
|
| 379 |
+
except KeyboardInterrupt:
|
| 380 |
+
print("\nReceived shutdown signal, cleaning up...")
|
| 381 |
+
except Exception as e:
|
| 382 |
+
print(f"Critical error: {str(e)}")
|
| 383 |
+
import traceback
|
| 384 |
+
print(traceback.format_exc())
|
| 385 |
+
finally:
|
| 386 |
+
if crawler:
|
| 387 |
+
print("Closing database connection...")
|
| 388 |
+
crawler.conn.close()
|
| 389 |
+
print("Cleanup completed")
|
| 390 |
+
|
| 391 |
+
if __name__ == "__main__":
|
| 392 |
+
print("Starting crawler...")
|
| 393 |
+
asyncio.run(main())
|
03Added/users.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
zlexdl,HM010169,btcyusheng,fairyclub777,WY_mask,btc100000015252,0xpcp_,Baili1018,nancy_c813
|