This time, we will deal with ** Twiiter API ** in Web API. If you use the Twiiter API, you will be able to perform the following two points automatically.
① Get posts that meet specific conditions ② Post automatically with your account
This time I will execute ①.
I will automatically acquire the posted images from the Tweets of ** Mia Nanasawa ** who is active as an AV actress and is indebted to me the most.
consumer_key = "???"
consumer_secret = "???"
access_token = "???"
access_token_secret = "???"
#Get each???Substitute in.
For details of the code below https://kurozumi.github.io/tweepy/getting_started.html#hello-tweepy It is written in.
def show_user_profile():
user = api.get_user('mia_nanasawa')
print(user.screen_name) #Get account name
print(user.followers_count) #Get followers
From the Twitter image below, you can see that you have correctly obtained ** account name ** and ** number of followers **.
How to use user_timeline https://kurozumi.github.io/tweepy/api.html It is written in.
def show_media_url():
user_id = "mia_nanasawa"
statuses = api.user_timeline(id=user_id, count=4)
count = 1
for status in statuses:
for entity in status.extended_entities["media"]:
img_url = entity["media_url"]
print(img_url)
break
def download_image(url, file_path):
r = requests.get(url, stream=True)
if r.status_code == 200:
with open(file_path, "wb") as f:
f.write(r.content)
How to use Cursor https://kurozumi.github.io/tweepy/cursor_tutorial.html It is written in.
def main():
user_id = "mia_nanasawa"
for page in tweepy.Cursor(api.user_timeline, id=user_id).pages(20):
for status in page:
try:
for media in status.extended_entities["media"]:
media_id = media["id"]
img_url = media["media_url"]
print(media_id)
print(img_url)
#In the current directory"Create an "images folder".
download_image(url=img_url, file_path="./images/{}.jpg ".format(media_id))
#If an error occurs during the try, an exception will be output and the loop will be executed.
except Exception as e:
print(e)
#There may be an error when tweeting with a video.
if __name__ == "__main__":
main()
From the above output, you can see that some ** error handling ** has occurred. It is likely that the Tweet contains ** videos ** rather than image files. (By the way, the tweeted image has been acquired correctly.)
I was able to confirm that it was saved correctly in the images file.
Now you have an eye candy.
Recommended Posts