Dwi*_*ght 6 python twitter tweepy twitterapi-python
我正在尝试从 geeksforgeeks 复制此代码片段,只不过它使用 Twitter API v1.1 的 oauth,而我使用 API v2。
# the screen name of the user
screen_name = "PracticeGfG"
# fetching the user
user = api.get_user(screen_name)
# fetching the ID
ID = user.id_str
print("The ID of the user is : " + ID)
OUTPUT:
The ID of the user is: 4802800777.
Run Code Online (Sandbox Code Playgroud)
这是我的:
import os
import tweepy
API_KEY = os.getenv('API_KEY')
API_KEY_SECRET = os.getenv('API_KEY_SECRET')
BEARER_TOKEN = os.getenv('BEARER_TOKEN')
ACCESS_TOKEN = os.getenv('ACCESS_TOKEN')
ACCESS_TOKEN_SECRET = os.getenv('ACCESS_TOKEN_SECRET')
screen_name = 'nytimes'
client = tweepy.Client(consumer_key=API_KEY, consumer_secret=API_KEY_SECRET, access_token=ACCESS_TOKEN, access_token_secret=ACCESS_TOKEN_SECRET)
user = client.get_user(screen_name)
id = user.id_str
print(id)
Run Code Online (Sandbox Code Playgroud)
当我运行我的程序时,它返回以下错误:
类型错误:get_user() 采用 1 个位置参数,但给出了 2 个。
你能给我提示我错过了什么吗?先谢谢了。
get_user有以下签名。
Client.get_user(*, id, username, user_auth=False, expansions, tweet_fields, user_fields)
Run Code Online (Sandbox Code Playgroud)
注意*. *用于强制调用者使用命名参数。例如,这行不通。
>>> def add(first, *, second):
... print(first, second)
...
>>> add(1, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: add() takes 1 positional argument but 2 were given
Run Code Online (Sandbox Code Playgroud)
但这会
>>> add(1, second=2)
1 2
Run Code Online (Sandbox Code Playgroud)
因此,要回答您的问题,您应该调用get_user这样的方法。
client.get_user(username=screen_name)
Run Code Online (Sandbox Code Playgroud)
小智 5
我相信 client.get_user(username=screen_name) 返回一个类,所以这个函数对我有用:
def return_twitterid(screen_name):
print("The screen name is: " + screen_name)
twitterid = client.get_user(username=screen_name)
print(type(twitterid)) #to confirm the type of object
print(f"The Twitter ID is {twitterid.data.id}.")
return
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9250 次 |
| 最近记录: |