我正在尝试使用 twikit python lib 来 webscrape X(以前称为 twitter)。
我无法验证 auth_token 是否过期。
以下是代码片段供您参考:
from twikit import Client, TooManyRequests
import time
from datetime import datetime
import json
import csv
from configparser import ConfigParser
from random import randint
import asyncio
import tracemalloc
import os
import jwt
import tracemalloc
tracemalloc.start()
# Login credentials
config = ConfigParser()
config.read('config.ini')
username = config['X']['username']
password = config['X']['password']
email = config['X']['email']
# Create a client
client = Client(language='en-US')
# Define the file path
cookies_file_path = 'cookies.json'
async def login_client():
await client.login(auth_info_1=username, auth_info_2=email, password=password)
if not os.path.exists(cookies_file_path):
# Function to login and generate new token
asyncio.run(login_client())
client.save_cookies(cookies_file_path)
else:
# Check if the auth_token is valid or expired
token = jwt.decode(client.auth_token, verify=False)['exp']
current_time = int(datetime.now().timestamp())
if token < current_time:
# Generate a new token
asyncio.run(login_client())
client.save_cookies(cookies_file_path)
else:
# Load existing cookies
client.load_cookies(cookies_file_path)
# Get tweets
MINIMUM_TWEETS = 10
QUERY = 'Nvidia stock' #input("Enter the query: ")
tweet_data = [] # [tweet_count, tweet.user.name, tweet.text, tweet.created_at, tweet.updated_at, tweet.retweet_count, tweet.favorite_count]
global tweet_count
tweet_count = 0
async def get_tweets():
tweets = await client.search_tweet(query=QUERY, product='Top', count=MINIMUM_TWEETS)
global tweet_count
for tweet in tweets:
tweet_count += 1
tweet_data = [tweet_count, tweet.user.name, tweet.text, tweet.created_at, tweet.retweet_count, tweet.favorite_count]
print(tweet_data)
# with open('tweets.csv', 'a', newline='') as file:
# writer = csv.writer(file)
# writer.writerow(tweet_data)
asyncio.run(get_tweets())
print(f"Total tweets: {tweet_count}")
到目前为止我做得很好,但我想要使用保存在 cookies.json 中的 auth_token 进行验证。我想验证它是否过期,如果过期,则重新登录,或加载过去保存的cookie。
我一直在尝试使用 PyJwt Python lib 来解码 auth_token 并获取“exp”属性,但它需要一个 Secret_key。这就是我现在陷入困境的地方。我如何获得secret_key?我不知道从哪里得到它。我的意思是,我正在使用 twikit,所以我不会主动存储任何密钥并使用请求来执行任何 API 调用。
twikit 在与 X (Twitter) 交互时已经处理令牌验证。
您可能不需要手动检查或解码令牌。
您目前的做法是正确的。
信任 twikit 的 cookie/令牌管理库方法。
使用 verify_signature=False 是有风险的。