我正在编写一个简单的python程序,它使用twitter的tweepy和wget从twitter检索图像链接(例如: twitter.com/ExampleUsername/12345678),然后从链接下载图像。实际的方案运作良好,但有一个问题。虽然它对字典中的每个ID运行(如果有2个ID,它运行2次),但它不使用每个ID,因此脚本最终会查看字典上的最后一个id,然后从该ID下载图像,不管字典中有多少次有ID。有人知道如何使脚本对每个ID再次运行吗?
我想让程序查看第一个ID,获取它的图像链接,下载它,然后对下一个ID执行相同的操作,直到完成所有的ID。
#!/usr/bin/env python
# encoding: utf-8
import tweepy #https://github.com/tweepy/tweepy
import wget
#Twitter API credentials
consumer_key = "nice try :)"
consumer_secret = "nice try :)"
access_key = "nice try :)"
access_secret = "my, this joke is getting really redundant"
def get_all_tweets():
#authorize twitter, initialize tweepy
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
id_list = [1234567890, 0987654321]
# Hey StackOverflow, these are example ID's. They won't work as they're not real twitter ID's, so if you're gonna run this yourself, you'll want to find some twitter IDs on your own
# tweets = api.statuses_lookup(id_list)
for i in id_list:
tweets = []
tweets.extend(api.statuses_lookup(id_=id_list, include_entities=True))
for tweet in tweets:
spacefiller = (1+1)
# this is here so the loop runs, if it doesn't the app breaks
a = len(tweets)
print(tweet.entities['media'][0]['media_url'])
url = tweet.entities['media'][0]['media_url']
wget.download(url)
get_all_tweets()
谢谢,~CS
发布于 2020-04-15 07:33:19
我想出来了!我知道那个循环被用来做什么..。
我将从a = len(tweets
到wget.download(url)
的所有内容都移到for tweet in tweets:
循环中,并删除了for i in id_list:
循环。
多亏了tdelany,这个节目现在开始工作了!谢谢大家!
这是新代码,如果有人想要的话:
#!/usr/bin/env python
# encoding: utf-8
import tweepy #https://github.com/tweepy/tweepy
import wget
#Twitter API credentials
consumer_key = "nice try :)"
consumer_secret = "nice try :)"
access_key = "nice try :)"
access_secret = "my, this joke is getting really redundant"
def get_all_tweets():
#authorize twitter, initialize tweepy
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
id_list = [1234567890, 0987654321]
# Hey StackOverflow, these are example ID's. They won't work as they're not real twitter ID's, so if you're gonna run this yourself, you'll want to find some twitter IDs on your own
tweets = []
tweets.extend(api.statuses_lookup(id_=id_list, include_entities=True))
for tweet in tweets:
a = len(tweets)
print(tweet.entities['media'][0]['media_url'])
url = tweet.entities['media'][0]['media_url']
wget.download(url)
get_all_tweets()
发布于 2020-04-15 07:12:37
有一件奇怪的事情是,我在外部循环中声明的变量从未在on之后使用。你的代码不应该是
tweets.extend(api.statuses_lookup(id_=i, include_entities=True))
而不是你写的id_=id_list?
https://stackoverflow.com/questions/61223121
复制相似问题