Ajwct

Twitter Image Scraper

Feb 9th, 2024
1,491
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.17 KB | None | 0 0
  1. import requests
  2. from bs4 import BeautifulSoup
  3. import os
  4.  
  5. def download_images(username, num_images):
  6.     url = f"https://twitter.com/{username}"
  7.     response = requests.get(url)
  8.     if response.status_code == 200:
  9.         soup = BeautifulSoup(response.content, 'html.parser')
  10.         image_tags = soup.find_all('img')
  11.         image_count = 0
  12.         if not os.path.exists(username):
  13.             os.makedirs(username)
  14.         for img in image_tags:
  15.             image_url = img.get('src')
  16.             if image_url and 'media' in image_url:
  17.                 filename = f"{username}_{image_count}.jpg"
  18.                 with open(os.path.join(username, filename), 'wb') as f:
  19.                     f.write(requests.get(image_url).content)
  20.                 image_count += 1
  21.                 if image_count >= num_images:
  22.                     break
  23.         print(f"Downloaded {image_count} images.")
  24.     else:
  25.         print(f"Failed to retrieve Twitter page for {username}.")
  26.  
  27. if __name__ == "__main__":
  28.     username = input("Enter the username of the Twitter account: ")
  29.     num_images = int(input("Enter the number of images to download: "))
  30.     download_images(username, num_images)
  31.  
Tags: twitter image
Advertisement
Add Comment
Please, Sign In to add comment