import os
import random
import time
import requests
import urllib.request
from bs4 import BeautifulSoup


def main():
    with open('urls.txt', 'r') as file:
        urls = file.readlines()

    headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:133.0) Gecko/20100101 Firefox/133.0'}
    for url in urls:
        time.sleep(random.randint(200, 1500) / 1000)
        url = url.strip()  # Remove any leading/trailing whitespace
        if url:
            download_image(url, headers)


# Function to process each URL and download the image
def download_image(url, headers):
    try:
        session = requests.Session()
        session.headers.update(headers)
        
        response = session.get(url)
        session.cookies.update(response.cookies)
        
        response = session.get(url)
        soup = BeautifulSoup(response.text, 'html.parser')
        player_div = soup.find('div', id='player')

        if player_div:
            img_tag = player_div.find('img')
            if img_tag and 'src' in img_tag.attrs:
                img_url = img_tag['src']
                img_name = os.path.basename(img_url)
                img_response = session.get(img_url, headers=headers, cookies=session.cookies)
                with open(img_name, 'wb') as img_file:
                    img_file.write(img_response.content)

                print(f'Image from {url} downloaded as {img_name}')

            else:
                print(f'No img tag found inside the player div for {url}.')
        else:
            print(f'No div with id "player" found for {url}.')
    except Exception as e:
        print(f'Error processing {url}: {e}')


if __name__ == "__main__":
    main()
