Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

session not loading. showing session load error #2254

Open
tiddu opened this issue May 12, 2024 · 1 comment
Open

session not loading. showing session load error #2254

tiddu opened this issue May 12, 2024 · 1 comment
Labels
question Question stale Issue is inactive for a long time

Comments

@tiddu
Copy link

tiddu commented May 12, 2024


from instaloader import Instaloader, Post
import time
import csv
import random  # Import random module for generating random sleep times
from datetime import datetime
import os  # Import os module to handle file and directory operations

# Add your Instagram username and password here
IG_USERNAME = 'username'
IG_PASSWORD = 'password'

# Custom folder path where downloads will be stored
CUSTOM_FOLDER_PATH = r"H:\files\redmi note 3\syncme\k20 pro moved old\Pictures\Instander\explore"

# Session file path
SESSION_FILE = CUSTOM_FOLDER_PATH + '/session-' + IG_USERNAME

# Initialize Instaloader with a custom directory pattern for downloads
L = Instaloader()
L.dirname_pattern = os.path.join(CUSTOM_FOLDER_PATH, "explore_posts")

# Ensure the directory for the session file exists
os.makedirs(os.path.dirname(SESSION_FILE), exist_ok=True)

# Try loading the session from the file, or login with credentials if the session file does not exist
if os.path.exists(SESSION_FILE):
    try:
        # Attempt to load the session
        if L.load_session_from_file(IG_USERNAME, SESSION_FILE):
            print("Logged in using session file.")
        else:
            # Session exists but failed to load properly
            raise Exception("Failed to load session.")
    except Exception as e:
        print(f"Session error: {e}")
        # Log in with credentials if the session file does not work
        L.login(IG_USERNAME, IG_PASSWORD)
        L.save_session_to_file(SESSION_FILE)
        print("Logged in using credentials and session saved.")
else:
    # No session file exists, login is necessary
    L.login(IG_USERNAME, IG_PASSWORD)
    L.save_session_to_file(SESSION_FILE)
    print("Logged in using credentials and session saved.")


# Enabling built-in sleep feature to moderate request rate
L.sleep = True

# Function to append post data to a CSV file
def append_to_csv(post):
    with open(os.path.join(CUSTOM_FOLDER_PATH, 'explore_posts_data.csv'), mode='a', newline='', encoding='utf-8') as file:
        writer = csv.writer(file)
        # Write data: post ID, number of likes, number of comments, and download timestamp
        writer.writerow([post.shortcode, post.likes, post.comments, datetime.now()])

# Main loop to process Instagram posts
while True:
    try:
        explore_posts = L.get_explore_posts()
        count = 0
        for post in explore_posts:
            if count >= 100:  # Limit to 30 posts per hour
                break
            # Download all posts including videos
            L.download_post(post, 'explore')
            append_to_csv(post)
            count += 1
            # Random sleep between post downloads to minimize rate limit risks
            time.sleep(random.uniform(5, 15))
        print("Explore posts download completed.")
    except Exception as e:
        print(f"Error fetching explore posts: {e}")
        # Handle rate limiting and other errors by pausing
        if '400' in str(e) or '429' in str(e):
            print("Rate limit error encountered, pausing for 2 minutes...")
            time.sleep(120)  # Pause for 2 minutes
        else:
            print("Unexpected error, pausing for 5 minutes...")
            time.sleep(300)  # Pause for 5 minutes to ensure not hitting the server too hard
    
    # Sleep for one hour before the next run
    time.sleep(3600)

this is my script.

@tiddu tiddu added the question Question label May 12, 2024
Copy link

github-actions bot commented Jun 3, 2024

There has been no activity on this question for an extended period of time. This issue will be closed after further 14 days of inactivity.

@github-actions github-actions bot added the stale Issue is inactive for a long time label Jun 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Question stale Issue is inactive for a long time
Projects
None yet
Development

No branches or pull requests

1 participant