Tuesday, November 26, 2024

Scrape Pinterest Part 1


I am interested in writing a python script to webscrape my pinterest account and pull videos and Gifs from a date range. Pintertest does offer an API that does allow a Python script to do what I want. I even got Microsoft Copilot to generate a working script but using the API is really expensive. Therefore I found another article for that allows you to work around the API. See the following tutorial from Extracting Data from Pinterest using BeautifulSoup, Python. I also hope to use AI to put the downloaded pictures or video in folders for archiving. I wanted to do both in one script but I may have to do a separate script for training a model and organizing files into appropriate folders. Below is code that Microsoft Copilot genereated with a little editing from me.

#Write a python script that uses pinterest api to put pins into the correct board from the last seven days. If there is no board put the pin into the Unknown board.

import datetime, os

try:
    from pinterest_api import Pinterest
except:
    os.system("pip install pinterest-api")
    from pinterest_api import Pinterest

# Initialize Pinterest API
pinterest = Pinterest(access_token='@#$$%#@#')

# Get today's date and the date 7 days ago
today = datetime.datetime.now()
week_ago = today - datetime.timedelta(days=7)

# Get pins from the last 7 days
pins = pinterest.get_user_pins()

# Filter pins from the last 7 days
recent_pins = [pin for pin in pins if week_ago <= datetime.datetime.strptime(pin['created_at'], '%Y-%m-%dT%H:%M:%S') <= today]

# Function to add pin to board
def add_pin_to_board(pin, board_name):
    boards = pinterest.get_boards()
    board = next((board for board in boards if board['name'] == board_name), None)
   
    if board is None:
        # Create 'Unknown' board if it doesn't exist
        if board_name == 'Unknown':
            board = pinterest.create_board(name='Unknown', description='Pins without a specific board')
        else:
            print(f"Board '{board_name}' not found.")
            return
       
    pinterest.create_pin(board_id=board['id'], note=pin['note'], link=pin['link'], image_url=pin['image']['original']['url'])

# Iterate through recent pins and add them to the correct board or 'Unknown'
for pin in recent_pins:
    board_name = pin['board']['name'] if 'board' in pin else 'Unknown'
    add_pin_to_board(pin, board_name)

print("Pins have been organized.")

I did find a No-Code solution That I am planning to explore to make a browser bot:

Scrape Pinterest data without code

No comments: