import requests
import time
import csv
import json
import re
from datetime import datetime
import logging
import os
from bs4 import BeautifulSoup
import random
from urllib.parse import quote
Try to import selenium for browser automation fallback
try:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
SELENIUM_AVAILABLE = True
except ImportError:
SELENIUM_AVAILABLE = False
Args:
reel_url: URL of the Instagram reel to track
output_file: CSV file to store the data
"""
self.reel_url = reel_url
self.output_file = output_file
# User agents to rotate
self.user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:89.0) Gecko/20100101 Firefox/89.0'
]
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('instagram_scraper.log'),
logging.StreamHandler()
]
)
self.logger = logging.getLogger(__name__)
# Initialize CSV file
self._initialize_csv()
# Session for maintaining cookies
self.session = requests.Session()
def _initialize_csv(self):
"""Initialize CSV file with headers if it doesn't exist"""
if not os.path.exists(self.output_file):
with open(self.output_file, 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow([
'timestamp',
'datetime',
'likes_count',
'comments_count',
'views_count',
'status'
])
self.logger.info(f"Created new CSV file: {self.output_file}")
def _get_random_headers(self):
"""Get random headers to avoid detection"""
return {
'User-Agent': random.choice(self.user_agents),
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
}
def _extract_json_data(self, html_content):
"""Extract JSON data from Instagram page"""
try:
# Look for shared data in script tags
pattern = r'window\._sharedData\s*=\s*({.*?});'
match = re.search(pattern, html_content)
if match:
return json.loads(match.group(1))
# Alternative pattern for newer Instagram versions
pattern = r'window\.__additionalDataLoaded\(\'[^\']+\',\s*({.*?})\);'
matches = re.findall(pattern, html_content)
if matches:
return json.loads(matches[0])
return None
except Exception as e:
self.logger.error(f"Error extracting JSON data: {e}")
return None
def _extract_likes_from_html(self, html_content):
"""Extract likes count from HTML using multiple methods"""
try:
soup = BeautifulSoup(html_content, 'html.parser')
# Method 1: Target the exact span with Instagram likes classes
likes_classes = [
'xdj266r', 'x14z9mp', 'xat24cr', 'x1lziwak', 'xexx8yu',
'xyri2b', 'x18d9i69', 'x1c1uobl', 'x1hl2dhg', 'x16tdsg8',
'x1vvkbs'
]
# Look for span with these specific classes
for span in soup.find_all('span', class_=likes_classes):
text = span.get_text().strip()
if re.match(r'^\d+(?:,\d+)*$', text): # Pure number format like "13,572"
likes_count = int(text.replace(',', ''))
self.logger.info(f"Found likes via exact classes: {likes_count}")
return likes_count
# Method 2: Look for spans with any combination of these classes
for span in soup.find_all('span'):
span_classes = span.get('class', [])
# Check if span has at least 3 of our target classes
matching_classes = len([c for c in likes_classes if c in span_classes])
if matching_classes >= 3:
text = span.get_text().strip()
if re.match(r'^\d+(?:,\d+)*$', text):
likes_count = int(text.replace(',', ''))
self.logger.info(f"Found likes via partial class match ({matching_classes} classes): {likes_count}")
return likes_count
# Method 3: Look for any span with comma-separated numbers (Instagram format)
for span in soup.find_all('span'):
text = span.get_text().strip()
if re.match(r'^\d{1,3}(?:,\d{3})*$', text): # Format like 13,572 or 1,234,567
likes_count = int(text.replace(',', ''))
# Only consider it if it's a reasonable likes count (not too small, not too big)
if 1 <= likes_count <= 100000000: # Between 1 and 100M
self.logger.info(f"Found potential likes via number format: {likes_count}")
return likes_count
# Method 4: Use the original long CSS selector
css_selector = "#mount_0_0_pK > div > div > div.x9f619.x1n2onr6.x1ja2u2z > div > div > div.x78zum5.xdt5ytf.x1t2pt76.x1n2onr6.x1ja2u2z.x10cihs4 > div.x9f619.xvbhtw8.x78zum5.x15mokao.x1ga7v0g.x16uus16.xbiv7yw.x1uhb9sk.x1plvlek.xryxfnj.x1c4vz4f.x2lah0s.xdt5ytf.xqjyukv.x1qjc9v5.x1oa3qoh.x1qughib > div.xvc5jky.xh8yej3.x10o80wk.x14k21rp.x17snn68.x6osk4m.x1porb0y.x8vgawa > section > main > div > article > div:nth-child(3) > div > div:nth-child(1) > section.x1e56ztr.x1xmf6yo > div > div > span > a > span > span"
likes_element = soup.select_one(css_selector)
if likes_element:
likes_text = likes_element.get_text().strip()
self.logger.info(f"Found element via CSS selector: '{likes_text}'")
likes_match = re.search(r'(\d+(?:,\d+)*)', likes_text)
if likes_match:
likes_count = int(likes_match.group(1).replace(',', ''))
self.logger.info(f"Extracted likes from CSS selector: {likes_count}")
return likes_count
# Method 5: Search for likes in context (near "like" text)
for element in soup.find_all(['button', 'a', 'div']):
text = element.get_text().lower()
aria_label = element.get('aria-label', '').lower()
if 'like' in text or 'like' in aria_label:
# Look for numbers in this element or nearby elements
for span in element.find_all('span'):
span_text = span.get_text().strip()
if re.match(r'^\d+(?:,\d+)*$', span_text):
likes_count = int(span_text.replace(',', ''))
self.logger.info(f"Found likes near 'like' context: {likes_count}")
return likes_count
# Method 6: Debug - print all spans with numbers
self.logger.info("DEBUG: Looking for all spans with number patterns...")
for span in soup.find_all('span'):
text = span.get_text().strip()
classes = span.get('class', [])
if re.search(r'\d+', text) and len(text) < 20:
self.logger.info(f"DEBUG Span: text='{text}', classes={classes[:5]}...") # Show first 5 classes
self.logger.warning("No likes count found with any method")
return 0
except Exception as e:
self.logger.error(f"Error extracting likes from HTML: {e}")
return 0
def scrape_with_selenium(self):
"""Fallback method using Selenium for JavaScript-heavy content"""
if not SELENIUM_AVAILABLE:
self.logger.error("Selenium not available. Install with: pip install selenium")
return None
try:
# Setup Chrome options
chrome_options = Options()
chrome_options.add_argument('--headless') # Run in background
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--window-size=1920,1080')
chrome_options.add_argument(f'--user-agent={random.choice(self.user_agents)}')
# Initialize driver
driver = webdriver.Chrome(options=chrome_options)
driver.get(self.reel_url)
# Wait for page to load
time.sleep(5)
# Try multiple selectors for likes
likes_selectors = [
'button span span', # Common likes button
'[aria-label*="like"] span',
'span[class*="_ac2a"]',
'span:contains("like")',
'button[aria-label*="like"]',
]
likes_count = 0
for selector in likes_selectors:
try:
if 'contains' in selector:
# Use XPath for contains
xpath = f"//span[contains(text(), 'like')]"
elements = driver.find_elements(By.XPATH, xpath)
else:
elements = driver.find_elements(By.CSS_SELECTOR, selector)
for element in elements:
text = element.text.strip()
aria_label = element.get_attribute('aria-label') or ''
# Look for numbers in text or aria-label
for content in [text, aria_label]:
if content and 'like' in content.lower():
match = re.search(r'(\d+(?:,\d+)*)', content)
if match:
likes_count = int(match.group(1).replace(',', ''))
self.logger.info(f"Selenium found likes: {likes_count}")
driver.quit()
return likes_count
except Exception as e:
continue
# If no likes found, get page source for debugging
page_source = driver.page_source
with open('selenium_debug.html', 'w', encoding='utf-8') as f:
f.write(page_source)
self.logger.info("Selenium page source saved to selenium_debug.html")
driver.quit()
return 0
except Exception as e:
self.logger.error(f"Selenium scraping failed: {e}")
return None
def scrape_reel_data(self):
"""Scrape reel data from Instagram"""
try:
headers = self._get_random_headers()
# Add random delay to avoid rate limiting
time.sleep(random.uniform(2, 5))
response = self.session.get(self.reel_url, headers=headers, timeout=30)
response.raise_for_status()
html_content = response.text
self.logger.info(f"Page loaded successfully, content length: {len(html_content)}")
# Save HTML content for debugging (optional)
# with open('debug_page.html', 'w', encoding='utf-8') as f:
# f.write(html_content)
# Extract JSON data
json_data = self._extract_json_data(html_content)
likes_count = 0
comments_count = 0
views_count = 0
if json_data:
try:
# Navigate through JSON structure to find post data
entry_data = json_data.get('entry_data', {})
post_page = entry_data.get('PostPage', [])
if post_page and len(post_page) > 0:
media = post_page[0].get('graphql', {}).get('shortcode_media', {})
likes_count = media.get('edge_media_preview_like', {}).get('count', 0)
comments_count = media.get('edge_media_to_comment', {}).get('count', 0)
views_count = media.get('video_view_count', 0)
self.logger.info(f"Extracted from JSON - Likes: {likes_count}, Comments: {comments_count}")
except Exception as e:
self.logger.warning(f"JSON parsing failed, falling back to HTML parsing: {e}")
# Always try HTML parsing (prioritize it)
html_likes = self._extract_likes_from_html(html_content)
if html_likes > 0:
likes_count = html_likes
self.logger.info(f"Using HTML extracted likes: {likes_count}")
elif likes_count == 0:
self.logger.warning("No likes found in HTML, trying Selenium...")
# Try Selenium as fallback
selenium_likes = self.scrape_with_selenium()
if selenium_likes and selenium_likes > 0:
likes_count = selenium_likes
self.logger.info(f"Using Selenium extracted likes: {likes_count}")
else:
self.logger.warning("No likes found in either HTML or Selenium")
return {
'likes_count': likes_count,
'comments_count': comments_count,
'views_count': views_count,
'status': 'success'
}
except requests.exceptions.RequestException as e:
self.logger.error(f"Request failed: {e}")
return {
'likes_count': 0,
'comments_count': 0,
'views_count': 0,
'status': f'request_error: {str(e)}'
}
except Exception as e:
self.logger.error(f"Scraping failed: {e}")
return {
'likes_count': 0,
'comments_count': 0,
'views_count': 0,
'status': f'error: {str(e)}'
}
def save_data_point(self, data):
"""Save a data point to CSV file"""
timestamp = time.time()
datetime_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
row_data = [
timestamp,
datetime_str,
data['likes_count'],
data['comments_count'],
data['views_count'],
data['status']
]
try:
with open(self.output_file, 'a', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(row_data)
self.logger.info(f"Data saved: {datetime_str} - Likes: {data['likes_count']}")
except Exception as e:
self.logger.error(f"Failed to save data: {e}")
def track_likes(self, duration_hours=24, interval_minutes=5):
"""
Track likes for specified duration
Args:
duration_hours: How long to track (in hours)
interval_minutes: Interval between checks (in minutes)
"""
interval_seconds = interval_minutes * 60
total_iterations = (duration_hours * 3600) // interval_seconds
self.logger.info(f"Starting tracking for {duration_hours} hours with {interval_minutes}-minute intervals")
self.logger.info(f"Total iterations planned: {total_iterations}")
for i in range(total_iterations):
try:
self.logger.info(f"Iteration {i+1}/{total_iterations}")
# Scrape data
data = self.scrape_reel_data()
# Save data
self.save_data_point(data)
# Wait for next iteration (except for the last one)
if i < total_iterations - 1:
self.logger.info(f"Waiting {interval_minutes} minutes until next check...")
time.sleep(interval_seconds)
except KeyboardInterrupt:
self.logger.info("Tracking stopped by user")
break
except Exception as e:
self.logger.error(f"Error in iteration {i+1}: {e}")
# Continue with next iteration after a short delay
time.sleep(30)
self.logger.info("Tracking completed!")
# Create tracker instance
tracker = InstagramLikesScraper(REEL_URL)
# Start tracking for 24 hours, checking every 5 minutes
tracker.track_likes(duration_hours=24, interval_minutes=5)
print(f"Data saved to: {tracker.output_file}") in this appriach i want to run tjjis through a webapge where we enetr the link and the strat capturing and we can see the cpatuerd results after presing continuosly for each time dealy and selected time period like 24 hours 5 min delay and then a export likes option button
Assistant
Got it! You want to take this Python script-based Instagram reel likes scraper and turn it into a web application with a user interface where:
A user can enter the Instagram reel URL.
Select or input the tracking duration (e.g., 24 hours).
Select or input the interval (e.g., 5 minutes).
Start the tracking process from the webpage.
See the ongoing results on the webpage as the scraper captures data each interval.
Export/save the captured data on demand (e.g., by clicking an "Export Likes" button).
How to implement this?
We will make a simple Flask web application wrapping your scraping logic with:
A form to input URL, duration, interval.
Start/stop button to control the scraper.
Show captured data live on the page (auto-updating via AJAX/polling).
A button to export/download captured data (CSV).
Step-by-step implementation approach:
1. Separate scraping logic from tracking UI
You already have the scraping logic encapsulated inside InstagramLikesScraper. We'll reuse that as a backend service.
2. Create Flask app
python
User
canw e use straemlit
Assistant
Absolutely! Streamlit is a great choice for quickly building interactive data apps in Python, especially for things like your Instagram likes scraper where you want input controls, visual feedback, and export functionality without building a full web backend manually.
Advantages of using Streamlit here:
Easy UI with sliders, text inputs, buttons.
Fast refresh / rerun on user interaction.
Real-time updates with st.empty() or similar.
File download with st.download_button.
No need for explicit threading or Flask backend. (Though for long-running background, threading or async would still help.)
How to implement your Instagram scraper interface with Streamlit
Simplified approach:
User inputs the reel URL, duration, and interval.
When user clicks Start, run tracking in the session.
Show progress and captured data live.
Allow stopping.
Allow exporting CSV download.
Since Streamlit scripts rerun top-to-bottom on every interaction, for long-running scraping we need to:
Use Python threading or async to run the scraper without blocking the UI.
Store captured data and scraper state in st.session_state.
Use a loop with time.sleep() inside the background thread.
Use Streamlit elements like st.table() or st.dataframe() for showing live data.
Example Streamlit implementation
Save this to app.py (assuming your InstagramLikesScraper class is importable):
python
User
isnated of importing can we directly use that calss in its code itself
Assistant
Yes! You can absolutely include your whole InstagramLikesScraper class code directly inside the Streamlit script instead of importing it. This can make your code self-contained in a single file, easier for quick testing or deployment without juggling multiple files.
How to do it?
Copy your entire InstagramLikesScraper class code (everything from class InstagramLikesScraper: ... down to the end of the class)
Paste it at the top of your app.py Streamlit script (before you use it).
Example structure:
python
import streamlit as st
import threading
import time
import pandas as pd
# ... other imports you need, requests, bs4, etc.
# ===== Paste your full InstagramLikesScraper class here =====
class InstagramLikesScraper:
def __init__(self, reel_url: str, output_file: str = 'instagram_likes_data.csv'):
# your class code here ...
pass
# all methods inside the class...
# ===========================================================
# Then your Streamlit app code, e.g.
# Initialize session state
if 'tracking_active' not in st.session_state:
st.session_state.tracking_active = False
if 'captured_data' not in st.session_state:
st.session_state.captured_data = []
if 'scraper_thread' not in st.session_state:
st.session_state.scraper_thread = None
def run_tracking(reel_url, duration_hours, interval_minutes):
scraper = InstagramLikesScraper(reel_url, output_file='output_data.csv')
st.session_state.tracking_active = True
st.session_state.captured_data = []
# ... same code as before ...
# Your Streamlit UI code follows...
Things to keep in mind:
The script file will be bigger, but everything runs as one Streamlit app now.
Make sure you have all necessary dependencies installed (requests, beautifulsoup4, selenium etc.) for your InstagramLikesScraper.
If your scraper writes files, those files will appear relative to where you run Streamlit.
Streamlit reloads your script on each interaction, but because the long-running scraping is done in a background thread inside st.session_state, it won't block or restart scraping.
If you want, I can help you prepare a full single-file Streamlit app with your full scraping class embedded. Just say!
User
can we give me complte upadted cdoe
Assistant
Certainly! Below is a complete single-file Streamlit app that includes your entire InstagramLikesScraper class (copied and slightly adapted) embedded directly into the script.
How to run this:
Install required packages if you haven't:
bash
pip install streamlit requests beautifulsoup4
# If you want selenium fallback, also:
# pip install selenium
Save the following code into a file, e.g., instagram_likes_tracker.py.
Run:
bash
streamlit run instagram_likes_tracker.py
Complete self-contained Streamlit app:
python
User
2025-06-20 15:24:39,223 - INFO - Data saved: 2025-06-20 15:24:39 - Likes: 0 it is not capruing while in the prebious case when we imported then in the terminal it is shwing likes but then also in the fronetdn no rsponse
Assistant
Thanks for the additional information!
Your issue recap:
When running with the imported class, the likes counts are printed in terminal correctly.
When running the scraper code integrated inline in Streamlit, you see likes count = 0 in logs, and the Streamlit frontend keeps showing no data or zeros.
So: The scraper is not grabbing actual likes in the integrated case, but worked fine before.
Most likely causes & how to fix:
1) Current working directory & cache issues
Sometimes Instagram serves different content depending on headers, cookies, or session state.
When you import the class and run separately, it might benefit from sessions or cookies stored.
When embedded inline and running via Streamlit, the requests might be slightly different (headers, timing), or Instagram responds with limited/no data (e.g., blocked or login required).
What to do?
In your _get_random_headers() you already switch user agents randomly. That's good.
But Instagram aggressively blocks scraping - so it might be returning a zero-likes placeholder HTML.
2) Selenium fallback missing
Your integrated version currently does not contain the selenium fallback code (you omitted it to keep code minimal). Sometimes Instagram dynamically loads likes only with JS, so selenium fallback is needed.
Without selenium fallback, the scraper might get zero likes.
Also, the JSON parsing logic might fail silently due to page structure changes or missing data.
Suggestion: Add back the selenium fallback method and call it if zero likes are found in HTML + JSON.
3) Debugging - save HTML page source and analyze
To verify what's going on, add debug code inside _extract_likes_from_html or scrape_reel_data to save the raw HTML to a .html file when likes_count == 0 to inspect:
python
with open('debug_instagram_page.html', 'w', encoding='utf-8') as f:
f.write(html_content)
Then open this file in your browser and see if it contains the likes info or an error page/warning/etc.
User
indenttaion issues can u write complte upafetd code so i can just copy paste
Assistant
Certainly! Below is a complete updated Streamlit app with your full Instagram scraper class included inline, with indentation fixed and debugging additions to save the raw Instagram page HTML when likes are zero. This version also has better logging and status updates.
For brevity, I omitted selenium fallback here (can add if you want).
Save this as instagram_likes_tracker.py and run with streamlit run instagram_likes_tracker.py
python
User
not working but import requests
import time
import csv
import json
import re
from datetime import datetime
import logging
import os
from bs4 import BeautifulSoup
import random
from urllib.parse import quote
Try to import selenium for browser automation fallback
try:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
SELENIUM_AVAILABLE = True
except ImportError:
SELENIUM_AVAILABLE = False
Thanks for sharing the working standalone scraper code! Since you want to integrate this same working scraper into a Streamlit app, here’s a full working Streamlit app that includes your class inline, runs the scraping in a background thread, and displays live scraped data — essentially wrapping your working code in a Streamlit UI.
Complete Streamlit app with your exact class code embedded
Save as e.g. streamlit_instagram_tracker.py:
python
User
You can now view your Streamlit app in your browser.
2025-06-20 15:31:43.911 Thread 'Thread-7 (scraper_thread_func)': missing ScriptRunContext! This warning can be ignored when running in bare mode.
2025-06-20 15:31:43.912 Thread 'Thread-7 (scraper_thread_func)': missing ScriptRunContext! This warning can be ignored when running in bare mode.
2025-06-20 15:31:43.912 Thread 'Thread-7 (scraper_thread_func)': missing ScriptRunContext! This warning can be ignored when running in bare mode.
Exception in thread Thread-7 (scraper_thread_func):
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\streamlit\runtime\state\session_state.py", line 454, in getitem
return self._getitem(widget_id, key)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\streamlit\runtime\state\session_state.py", line 499, in _getitem
raise KeyError
KeyError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\streamlit\runtime\state\session_state_proxy.py", line 130, in getattr
return self[key]
~~~~^^^^^
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\streamlit\runtime\state\session_state_proxy.py", line 101, in getitem
return get_session_state()[key]
~~~~~~~~~~~~~~~~~~~^^^^^
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\streamlit\runtime\state\safe_session_state.py", line 96, in getitem
return self._state[key]
~~~~~~~~~~~^^^^^
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\streamlit\runtime\state\session_state.py", line 456, in getitem
raise KeyError(_missing_key_error_message(key))
KeyError: 'st.session_state has no key "data". Did you forget to initialize it? More info: https://docs.streamlit.io/develop/concepts/architecture/session-state#initialization'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 1075, in _bootstrap_inner
self.run()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 1012, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\Administrator\Desktop\views\intsa.py", line 158, in scraper_thread_func
st.session_state.data.clear()
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\streamlit\runtime\state\session_state_proxy.py", line 132, in
raise AttributeError(_missing_attr_error_message(key))
AttributeError: st.session_state has no attribute "data". Did you forget to initialize it? More info:
Assistant
The error occurs because Streamlit’s session_state is not thread-safe or accessible the way you expect inside a background thread. Threaded functions run outside of Streamlit’s rerun context and cannot safely read or mutate st.session_state.
Explanation of the error:
plaintext
AttributeError: st.session_state has no attribute "data". Did you forget to initialize it?
Your background thread calls st.session_state.data.clear(), but st.session_state is only meaningful inside the Streamlit main thread during script execution.
Trying to read or write st.session_state directly inside a background thread raises this error because Streamlit's session state depends on the context of a running Streamlit script, which is absent in that thread.
How to fix this properly?
Option 1: Use thread-safe data outside st.session_state
Create your own thread-safe global variable (e.g., a list or queue) to store scraped data.
Background thread updates that structure.
Streamlit periodically reads from it inside the main thread (like with st.experimental_rerun() or timer callbacks).
Example minimal fix:
Move your scraped data storage out of st.session_state for this purpose.
Certainly! Below is a fully updated, self-contained Streamlit app integrating your full InstagramLikesScraper class and fixing the session state threading issue by using a global thread-safe list with a lock. This code runs the scraper in a background thread, stores results safely, and displays live updates in Streamlit without accessing st.session_state inside the thread.
Save as e.g. instagram_tracker_threadsafe.py and run with:
bash
streamlit run instagram_tracker_threadsafe.py
python
User
2025-06-20 15:36:40,285 - INFO - Saved data point: 2025-06-20 15:36:40 Likes:0 not catpuring use the elmt selector to captur
Assistant
Thanks for the update!
If your scraper is still returning Likes: 0, it usually means that either:
Instagram’s page structure changed,
Or without authentication, Instagram is serving limited content,
Or your parser isn't finding the right element to extract likes.
You mentioned "use the element selector to capture likes."
The best way often is to target page elements with precise CSS selectors or XPath selectors, if available, or use Selenium to render the page (since Instagram heavily uses JS).
Since your standalone code includes a long CSS selector approach in _extract_likes_from_html, let's adapt this robust CSS selector approach directly in your Streamlit thread-safe app.
Updated _extract_likes_from_html method with CSS selector logic
Replace your _extract_likes_from_html method with this one (add explicit CSS selector fallback):
python
def _extract_likes_from_html(self, html_content):
try:
soup = BeautifulSoup(html_content, 'html.parser')
# Method 1: Try extracting by CSS selector - your provided long selector
css_selector = "#mount_0_0_pK > div > div > div.x9f619.x1n2onr6.x1ja2u2z > div > div > div.x78zum5.xdt5ytf.x1t2pt76.x1n2onr6.x1ja2u2z.x10cihs4 > div.x9f619.xvbhtw8.x78zum5.x15mokao.x1ga7v0g.x16uus16.xbiv7yw.x1uhb9sk.x1plvlek.xryxfnj.x1c4vz4f.x2lah0s.xdt5ytf.xqjyukv.x1qjc9v5.x1oa3qoh.x1qughib > div.xvc5jky.xh8yej3.x10o80wk.x14k21rp.x17snn68.x6osk4m.x1porb0y.x8vgawa > section > main > div > article > div:nth-child(3) > div > div:nth-child(1) > section.x1e56ztr.x1xmf6yo > div > div > span > a > span > span"
likes_element = soup.select_one(css_selector)
if likes_element:
likes_text = likes_element.get_text().strip()
if likes_text:
likes_number = int(likes_text.replace(',', ''))
self.logger.info(f"Likes found via CSS selector: {likes_number}")
return likes_number
# Method 2: fallback - find any span with comma numbers
for span in soup.find_all('span'):
text = span.get_text().strip()
if re.match(r'^\d{1,3}(?:,\d{3})*$', text):
likes = int(text.replace(',', ''))
if 1 <= likes <= 100_000_000:
self.logger.info(f"Likes found via span text: {likes}")
return likes
self.logger.warning("No likes found with CSS or span methods")
return 0
except Exception as e:
self.logger.error(f"Error extracting likes: {e}")
return 0
User
Capability
2025-06-20 15:36:46,352 - INFO - Selenium found likes: 13749
2025-06-20 15:36:48,498 - INFO - Using Selenium extracted likes: 13749
2025-06-20 15:36:48,500 - INFO - Data saved: 2025-06-20 15:36:48 - Likes: 13749
2025-06-20 15:36:48,500 - INFO - Waiting 5 minutes until next check... see ths is worikng for my code without streamlit import requests
import time
import csv
import json
import re
from datetime import datetime
import logging
import os
from bs4 import BeautifulSoup
import random
from urllib.parse import quote
Try to import selenium for browser automation fallback
try:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
SELENIUM_AVAILABLE = True
except ImportError:
SELENIUM_AVAILABLE = False
Great! Since your original standalone code with Selenium fallback works perfectly, and you want to integrate this working selenium-enabled scraperinside a Streamlit app with proper threading and live updates, here is a complete, updated Streamlit app that:
Embeds your full working InstagramLikesScraper (including Selenium fallback),
Runs the scraper in a background thread safely (without using st.session_state inside thread),
Displays live results,
Allows start/stop tracking,
Offers CSV export.
Full Streamlit app with Selenium fallback (adapted from your working scraper code)
python
User
2025-06-20 15:41:16,695 - INFO - No likes found via HTTP; trying Selenium fallback.
DevTools listening on ws://127.0.0.1:58355/devtools/browser/ad72553b-914e-4a56-abce-55082bd52833
WARNING: All log messages before absl::InitializeLog() is called are written to STDERR
I0000 00:00:1750414284.144767 19436 voice_transcription.cc:58] Registering VoiceTranscriptionCapability
2025-06-20 15:41:27,354 - INFO - Saved data point: 2025-06-20 15:41:27 Likes:0
Assistant
The log:
code
2025-06-20 15:41:16,695 - INFO - No likes found via HTTP; trying Selenium fallback.
...
2025-06-20 15:41:27,354 - INFO - Saved data point: 2025-06-20 15:41:27 Likes:0
indicates that Selenium fallback did run, but still returned Likes: 0.
This means:
Your Selenium code was triggered (good),
BUT Selenium scraping couldn’t find the likes count on the dynamically rendered page (or the selector failed),
So it logs Likes: 0 and saves zeros again.
What to check and how to fix:
1. Check the Selenium selectors
Instagram's HTML and class names are obfuscated and change frequently.
You may want to improve thread safety or use a job queue like Celery for production.
The above Flask app uses simple in-memory captured_data list and a CSV file to save data.
You can improve the UI/UX, pagination, and error handling further.
Install required packages for Flask and selenium if used by the scraper.
Run Flask app: python app.py and navigate to http://localhost:5000/
Summary
Flask frontend for form input and showing results.
Background thread runs tracking without blocking the web server.
Live updates via AJAX polling every 10 seconds.
Buttons to stop tracking and export the CSV data.
Utilizes your existing scraping class.
If you'd like, I can help you generate a full working example or package this in a Docker container. Would you like that?
import streamlit as st
import threading
import time
import pandas as pd
from your_scraper_file import InstagramLikesScraper # Replace with your module name
# Initialize session state
if 'tracking_active' not in st.session_state:
st.session_state.tracking_active = False
if 'captured_data' not in st.session_state:
st.session_state.captured_data = []
if 'scraper_thread' not in st.session_state:
st.session_state.scraper_thread = None
def run_tracking(reel_url, duration_hours, interval_minutes):
scraper = InstagramLikesScraper(reel_url, output_file='output_data.csv')
st.session_state.tracking_active = True
st.session_state.captured_data = []
interval_seconds = interval_minutes * 60
total_iterations = int((duration_hours * 3600) // interval_seconds)
for i in range(total_iterations):
if not st.session_state.tracking_active:
break
data = scraper.scrape_reel_data()
timestamp = time.time()
datetime_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))
record = {
'timestamp': timestamp,
'datetime': datetime_str,
'likes_count': data.get('likes_count', 0),
'comments_count': data.get('comments_count', 0),
'views_count': data.get('views_count', 0),
'status': data.get('status', '')
}
st.session_state.captured_data.append(record)
scraper.save_data_point(data)
time.sleep(interval_seconds)
st.session_state.tracking_active = False
st.title("Instagram Reel Likes Tracker")
with st.form("input_form"):
reel_url = st.text_input("Instagram Reel URL", value="", max_chars=200)
duration_hours = st.number_input("Duration (hours)", min_value=0.1, value=1.0)
interval_minutes = st.number_input("Interval (minutes)", min_value=0.1, value=0.1)
submitted = st.form_submit_button("Start Tracking")
if submitted:
if not reel_url:
st.error("Please enter a valid Instagram reel URL.")
else:
if not st.session_state.tracking_active:
# Start scraper thread
st.session_state.scraper_thread = threading.Thread(
target=run_tracking, args=(reel_url, duration_hours, interval_minutes),
daemon=True)
st.session_state.scraper_thread.start()
st.success("Started tracking!")
else:
st.warning("Tracking already active.")
# Show live tracking status and data
st.write(f"Tracking status: {'Active' if st.session_state.tracking_active else 'Inactive'}")
if st.session_state.captured_data:
df = pd.DataFrame(st.session_state.captured_data)
st.dataframe(df[['datetime', 'likes_count', 'comments_count', 'views_count', 'status']])
else:
st.write("No data captured yet.")
if st.session_state.tracking_active:
if st.button("Stop Tracking"):
st.session_state.tracking_active = False
st.success("Stopping tracking...")
if st.session_state.captured_data:
csv = pd.DataFrame(st.session_state.captured_data).to_csv(index=False).encode('utf-8')
st.download_button(
label="Export Likes Data as CSV",
data=csv,
file_name='instagram_likes_data.csv',
mime='text/csv'
)
How to run:
Save the above as app.py.
Make sure your InstagramLikesScraper code is in your_scraper_file.py or modify the import accordingly.
Install Streamlit if not installed:
bash
pip install streamlit
Run Streamlit:
bash
streamlit run app.py
Go to http://localhost:8501 in your browser.
What you get:
Text input for reel URL.
Numeric input for duration and interval.
Start tracking button that kicks off your scraper without blocking UI.
Live status display.
Live table showing the most recent data points.
Stop tracking button to interrupt.
CSV export button to download captured data anytime.
Important notes:
Because Streamlit reruns the script often, we store state in st.session_state, including scraper data and flags.
The scraper runs separately in a background thread so the UI remains responsive.
The time accuracy depends on Streamlit refresh - live updates might lag a few seconds.
For heavy usage or deployments, you might want to extend with queue/task manager (Celery/RQ) and a database.
If you want, I can help also prepare a complete package with your scraper integrated into Streamlit or help with deployment! Just ask!
import streamlit as st
import threading
import time
import csv
import json
import re
import logging
import os
from bs4 import BeautifulSoup
import random
import requests
from datetime import datetime
# Try to import selenium for browser automation fallback
try:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
SELENIUM_AVAILABLE = True
except ImportError:
SELENIUM_AVAILABLE = False
# === BEGIN InstagramLikesScraper class ===
class InstagramLikesScraper:
def __init__(self, reel_url: str, output_file: str = 'instagram_likes_data.csv'):
self.reel_url = reel_url
self.output_file = output_file
self.user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:89.0) Gecko/20100101 Firefox/89.0'
]
# Setup a basic logger
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('instagram_scraper.log'),
logging.StreamHandler()
]
)
self.logger = logging.getLogger(__name__)
self._initialize_csv()
self.session = requests.Session()
def _initialize_csv(self):
if not os.path.exists(self.output_file):
with open(self.output_file, 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow([
'timestamp',
'datetime',
'likes_count',
'comments_count',
'views_count',
'status'
])
self.logger.info(f"Created new CSV file: {self.output_file}")
def _get_random_headers(self):
return {
'User-Agent': random.choice(self.user_agents),
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
}
def _extract_json_data(self, html_content):
try:
pattern = r'window\._sharedData\s*=\s*({.*?});'
match = re.search(pattern, html_content)
if match:
return json.loads(match.group(1))
# Alternative pattern for newer Instagram versions
pattern = r'window\.__additionalDataLoaded\(\'[^\']+\',\s*({.*?})\);'
matches = re.findall(pattern, html_content)
if matches:
return json.loads(matches[0])
return None
except Exception as e:
self.logger.error(f"Error extracting JSON data: {e}")
return None
def _extract_likes_from_html(self, html_content):
try:
soup = BeautifulSoup(html_content, 'html.parser')
# Try multiple heuristics to find likes counts
# Method 1: Look for span having number pattern (like count)
likes_candidates = []
for span in soup.find_all('span'):
text = span.get_text().strip()
if re.match(r'^\d{1,3}(?:,\d{3})*$', text):
likes = int(text.replace(',', ''))
if 1 <= likes <= 100000000:
likes_candidates.append(likes)
if likes_candidates:
max_likes = max(likes_candidates)
self.logger.info(f"Extracted likes from HTML spans: {max_likes}")
return max_likes
# Could implement more methods here (your class has more complex tries)
self.logger.warning("No likes found in HTML")
return 0
except Exception as e:
self.logger.error(f"Error extracting likes from HTML: {e}")
return 0
def scrape_reel_data(self):
try:
headers = self._get_random_headers()
time.sleep(random.uniform(2, 5))
response = self.session.get(self.reel_url, headers=headers, timeout=30)
response.raise_for_status()
html_content = response.text
json_data = self._extract_json_data(html_content)
likes_count = 0
comments_count = 0
views_count = 0
if json_data:
try:
entry_data = json_data.get('entry_data', {})
post_page = entry_data.get('PostPage', [])
if post_page and len(post_page) > 0:
media = post_page[0].get('graphql', {}).get('shortcode_media', {})
likes_count = media.get('edge_media_preview_like', {}).get('count', 0)
comments_count = media.get('edge_media_to_comment', {}).get('count', 0)
views_count = media.get('video_view_count', 0)
except Exception as e:
self.logger.warning(f"JSON parsing failed, falling back: {e}")
# Try extracting likes from HTML also
html_likes = self._extract_likes_from_html(html_content)
if html_likes > 0:
likes_count = html_likes
return {
'likes_count': likes_count,
'comments_count': comments_count,
'views_count': views_count,
'status': 'success'
}
except requests.exceptions.RequestException as e:
self.logger.error(f"Request failed: {e}")
return {
'likes_count': 0,
'comments_count': 0,
'views_count': 0,
'status': f'request_error: {str(e)}'
}
except Exception as e:
self.logger.error(f"Scraping failed: {e}")
return {
'likes_count': 0,
'comments_count': 0,
'views_count': 0,
'status': f'error: {str(e)}'
}
def save_data_point(self, data):
timestamp = time.time()
datetime_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
row_data = [
timestamp,
datetime_str,
data['likes_count'],
data['comments_count'],
data['views_count'],
data['status']
]
try:
with open(self.output_file, 'a', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(row_data)
self.logger.info(f"Data saved: {datetime_str} - Likes: {data['likes_count']}")
except Exception as e:
self.logger.error(f"Failed to save data: {e}")
# === END InstagramLikesScraper class ===
# === Streamlit app code ===
# Initialize session state
if 'tracking_active' not in st.session_state:
st.session_state.tracking_active = False
if 'captured_data' not in st.session_state:
st.session_state.captured_data = []
if 'scraper_thread' not in st.session_state:
st.session_state.scraper_thread = None
def run_tracking(reel_url, duration_hours, interval_minutes):
scraper = InstagramLikesScraper(reel_url, output_file='output_data.csv')
st.session_state.tracking_active = True
st.session_state.captured_data = []
interval_seconds = interval_minutes * 60
total_iterations = int((duration_hours * 3600) // interval_seconds)
for i in range(total_iterations):
if not st.session_state.tracking_active:
break
data = scraper.scrape_reel_data()
timestamp = time.time()
datetime_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))
record = {
'timestamp': timestamp,
'datetime': datetime_str,
'likes_count': data.get('likes_count', 0),
'comments_count': data.get('comments_count', 0),
'views_count': data.get('views_count', 0),
'status': data.get('status', '')
}
st.session_state.captured_data.append(record)
scraper.save_data_point(data)
time.sleep(interval_seconds)
st.session_state.tracking_active = False
st.title("Instagram Reel Likes Tracker")
with st.form("input_form"):
reel_url = st.text_input("Instagram Reel URL", value="", max_chars=200)
duration_hours = st.number_input("Duration (hours)", min_value=0.1, value=1.0)
interval_minutes = st.number_input("Interval between checks (minutes)", min_value=0.1, value=0.1)
submitted = st.form_submit_button("Start Tracking")
if submitted:
if not reel_url:
st.error("Please enter a valid Instagram reel URL.")
else:
if not st.session_state.tracking_active:
st.session_state.scraper_thread = threading.Thread(
target=run_tracking, args=(reel_url, duration_hours, interval_minutes), daemon=True)
st.session_state.scraper_thread.start()
st.success("Started tracking!")
else:
st.warning("Tracking is already active.")
st.write(f"Tracking status: {'Active' if st.session_state.tracking_active else 'Inactive'}")
if st.session_state.captured_data:
import pandas as pd
df = pd.DataFrame(st.session_state.captured_data)
st.dataframe(df[['datetime', 'likes_count', 'comments_count', 'views_count', 'status']])
else:
st.write("No data captured yet.")
if st.session_state.tracking_active:
if st.button("Stop Tracking"):
st.session_state.tracking_active = False
st.success("Stopping tracking...")
if st.session_state.captured_data:
csv_contents = pd.DataFrame(st.session_state.captured_data).to_csv(index=False).encode('utf-8')
st.download_button(
label="Export Likes Data as CSV",
data=csv_contents,
file_name='instagram_likes_data.csv',
mime='text/csv'
)
Explanation:
The InstagramLikesScraper class is embedded at the top.
The Streamlit app manages scraper lifecycle through st.session_state.
Background scraping runs in a separate thread, updating shared state.
Results are shown in a dynamic table.
Stop button to safely request stopping.
Export button to download collected CSV data.
Caution:
Running this scraper repeatedly on Instagram URLs might get your IP blocked by Instagram because of scraping policies.
Use responsibly and carefully.
Selenium fallback is not included here for brevity; you can add it back from your original code if desired.
If you want me to add selenium or help with packaging for deployment, just ask!
4) Make sure you are not being rate-limited
Your delays (time.sleep(random.uniform(2,5))) might not be enough depending on calls frequency and Instagram rate limits.
Try increasing delays to 10-20 seconds for testing to see if it helps.
5) Thread-safe logging and Streamlit
Logging inside threads might get buffered or delayed. To see log output in real time, add explicit flushing or print statements alongside logger.info.
What changes should you do now?
Minimal patch with debug for scrape_reel_data:
Modify scrape_reel_data to save page source if likes are zero:
python
def scrape_reel_data(self):
try:
headers = self._get_random_headers()
time.sleep(random.uniform(2, 5))
response = self.session.get(self.reel_url, headers=headers, timeout=30)
response.raise_for_status()
html_content = response.text
# Save HTML for debugging
with open('debug_page.html', 'w', encoding='utf-8') as f:
f.write(html_content)
json_data = self._extract_json_data(html_content)
likes_count = 0
comments_count = 0
views_count = 0
if json_data:
try:
entry_data = json_data.get('entry_data', {})
post_page = entry_data.get('PostPage', [])
if post_page and len(post_page) > 0:
media = post_page[0].get('graphql', {}).get('shortcode_media', {})
likes_count = media.get('edge_media_preview_like', {}).get('count', 0)
comments_count = media.get('edge_media_to_comment', {}).get('count', 0)
views_count = media.get('video_view_count', 0)
except Exception as e:
self.logger.warning(f"JSON parsing failed, falling back: {e}")
# Try extracting likes from HTML also
html_likes = self._extract_likes_from_html(html_content)
if html_likes > 0:
likes_count = html_likes
if likes_count == 0:
self.logger.warning("Likes count is zero - check debug_page.html for page content.")
return {
'likes_count': likes_count,
'comments_count': comments_count,
'views_count': views_count,
'status': 'success'
}
except requests.exceptions.RequestException as e:
self.logger.error(f"Request failed: {e}")
return {
'likes_count': 0,
'comments_count': 0,
'views_count': 0,
'status': f'request_error: {str(e)}'
}
except Exception as e:
self.logger.error(f"Scraping failed: {e}")
return {
'likes_count': 0,
'comments_count': 0,
'views_count': 0,
'status': f'error: {str(e)}'
}
Then look at debug_page.html after running it once — this file shows exactly what Instagram returned.
Add Selenium fallback (optional, recommended)
If you want I can help you integrate the selenium fallback back — that often solves the "likes count = 0" problem when scraping Instagram.
Also verify your input URL
Make sure the Instagram reel URL you test in Streamlit is exactly the same as before, and publicly viewable (not private profile).
Summary of steps for you:
Add HTML debug saving in your scraper to see raw HTML.
Inspect that file to verify if likes info is present in HTML or if Instagram shows an error/Login block message.
Consider adding selenium fallback in the scraper for JS-driven content.
Add longer delays between requests during testing.
Print/log info both to console and Streamlit for debugging.
If you want, I can adjust your full Streamlit app example to include these debugging improvements and selenium fallback as well — just let me know!
import streamlit as st
import threading
import time
import csv
import json
import re
import logging
import os
from bs4 import BeautifulSoup
import random
import requests
from datetime import datetime
# === InstagramLikesScraper class ===
class InstagramLikesScraper:
def __init__(self, reel_url: str, output_file: str = 'instagram_likes_data.csv'):
self.reel_url = reel_url
self.output_file = output_file
self.user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:89.0) Gecko/20100101 Firefox/89.0'
]
# Setup a basic logger
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('instagram_scraper.log'),
logging.StreamHandler()
]
)
self.logger = logging.getLogger(__name__)
self._initialize_csv()
self.session = requests.Session()
def _initialize_csv(self):
if not os.path.exists(self.output_file):
with open(self.output_file, 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow([
'timestamp',
'datetime',
'likes_count',
'comments_count',
'views_count',
'status'
])
self.logger.info(f"Created new CSV file: {self.output_file}")
def _get_random_headers(self):
return {
'User-Agent': random.choice(self.user_agents),
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
}
def _extract_json_data(self, html_content):
try:
pattern = r'window\._sharedData\s*=\s*({.*?});'
match = re.search(pattern, html_content)
if match:
return json.loads(match.group(1))
pattern = r'window\.__additionalDataLoaded\(\'[^\']+\',\s*({.*?})\);'
matches = re.findall(pattern, html_content)
if matches:
return json.loads(matches[0])
return None
except Exception as e:
self.logger.error(f"Error extracting JSON data: {e}")
return None
def _extract_likes_from_html(self, html_content):
try:
soup = BeautifulSoup(html_content, 'html.parser')
likes_candidates = []
for span in soup.find_all('span'):
text = span.get_text().strip()
if re.match(r'^\d{1,3}(?:,\d{3})*$', text):
likes = int(text.replace(',', ''))
if 1 <= likes <= 100_000_000:
likes_candidates.append(likes)
if likes_candidates:
max_likes = max(likes_candidates)
self.logger.info(f"Extracted likes from HTML spans: {max_likes}")
return max_likes
self.logger.warning("No likes found in HTML")
return 0
except Exception as e:
self.logger.error(f"Error extracting likes from HTML: {e}")
return 0
def scrape_reel_data(self):
try:
headers = self._get_random_headers()
time.sleep(random.uniform(2, 5))
response = self.session.get(self.reel_url, headers=headers, timeout=30)
response.raise_for_status()
html_content = response.text
# Save raw HTML for debugging if likes come back zero
json_data = self._extract_json_data(html_content)
likes_count = 0
comments_count = 0
views_count = 0
if json_data:
try:
entry_data = json_data.get('entry_data', {})
post_page = entry_data.get('PostPage', [])
if post_page and len(post_page) > 0:
media = post_page[0].get('graphql', {}).get('shortcode_media', {})
likes_count = media.get('edge_media_preview_like', {}).get('count', 0)
comments_count = media.get('edge_media_to_comment', {}).get('count', 0)
views_count = media.get('video_view_count', 0)
except Exception as e:
self.logger.warning(f"JSON parsing failed, falling back: {e}")
html_likes = self._extract_likes_from_html(html_content)
if html_likes > 0:
likes_count = html_likes
if likes_count == 0:
# Save HTML if no likes found, to debug why
with open('debug_instagram_page.html', 'w', encoding='utf-8') as f:
f.write(html_content)
self.logger.warning("Likes count is zero - saved debug_instagram_page.html for review.")
return {
'likes_count': likes_count,
'comments_count': comments_count,
'views_count': views_count,
'status': 'success'
}
except requests.exceptions.RequestException as e:
self.logger.error(f"Request failed: {e}")
return {
'likes_count': 0,
'comments_count': 0,
'views_count': 0,
'status': f'request_error: {str(e)}'
}
except Exception as e:
self.logger.error(f"Scraping failed: {e}")
return {
'likes_count': 0,
'comments_count': 0,
'views_count': 0,
'status': f'error: {str(e)}'
}
def save_data_point(self, data):
timestamp = time.time()
datetime_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
row_data = [
timestamp,
datetime_str,
data['likes_count'],
data['comments_count'],
data['views_count'],
data['status']
]
try:
with open(self.output_file, 'a', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(row_data)
self.logger.info(f"Data saved: {datetime_str} - Likes: {data['likes_count']}")
except Exception as e:
self.logger.error(f"Failed to save data: {e}")
# === End of InstagramLikesScraper ===
# === Streamlit App ===
# Initialize Streamlit session state
if 'tracking_active' not in st.session_state:
st.session_state.tracking_active = False
if 'captured_data' not in st.session_state:
st.session_state.captured_data = []
if 'scraper_thread' not in st.session_state:
st.session_state.scraper_thread = None
def run_tracking(reel_url, duration_hours, interval_minutes):
scraper = InstagramLikesScraper(reel_url, output_file='output_data.csv')
st.session_state.tracking_active = True
st.session_state.captured_data = []
interval_seconds = interval_minutes * 60
total_iterations = int((duration_hours * 3600) // interval_seconds)
for i in range(total_iterations):
if not st.session_state.tracking_active:
break
data = scraper.scrape_reel_data()
timestamp = time.time()
datetime_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))
record = {
'timestamp': timestamp,
'datetime': datetime_str,
'likes_count': data.get('likes_count', 0),
'comments_count': data.get('comments_count', 0),
'views_count': data.get('views_count', 0),
'status': data.get('status', '')
}
st.session_state.captured_data.append(record)
scraper.save_data_point(data)
time.sleep(interval_seconds)
st.session_state.tracking_active = False
st.title("Instagram Reel Likes Tracker")
with st.form("input_form"):
reel_url = st.text_input("Instagram Reel URL", value="", max_chars=200)
duration_hours = st.number_input("Duration (hours)", min_value=0.1, value=0.1, format="%.1f")
interval_minutes = st.number_input("Interval between checks (minutes)", min_value=0.1, value=0.1, format="%.1f")
submitted = st.form_submit_button("Start Tracking")
if submitted:
if not reel_url:
st.error("Please enter a valid Instagram reel URL.")
else:
if not st.session_state.tracking_active:
st.session_state.scraper_thread = threading.Thread(
target=run_tracking, args=(reel_url, duration_hours, interval_minutes), daemon=True)
st.session_state.scraper_thread.start()
st.success("Started tracking!")
else:
st.warning("Tracking is already active.")
st.write(f"Tracking status: {'Active' if st.session_state.tracking_active else 'Inactive'}")
if st.session_state.captured_data:
import pandas as pd
df = pd.DataFrame(st.session_state.captured_data)
st.dataframe(df[['datetime', 'likes_count', 'comments_count', 'views_count', 'status']])
else:
st.write("No data captured yet.")
if st.session_state.tracking_active:
if st.button("Stop Tracking"):
st.session_state.tracking_active = False
st.success("Stopping tracking...")
if st.session_state.captured_data:
csv_contents = pd.DataFrame(st.session_state.captured_data).to_csv(index=False).encode('utf-8')
st.download_button(
label="Export Likes Data as CSV",
data=csv_contents,
file_name='instagram_likes_data.csv',
mime='text/csv'
)
What this does:
Your full scraper lives inside the same file, no import needed.
When likes_count is zero, it saves a debug HTML (debug_instagram_page.html) to check what Instagram actually returns.
App runs the scraper in a background thread so the UI remains responsive.
You can start/stop tracking.
Data is displayed live and you can export CSV anytime.
Tips for debugging:
Open the generated debug_instagram_page.html in a browser right after you get zeros. Check if Instagram shows actual likes or some "Login Required" / block page.
Instagram is very anti-scraping. If you see login prompt in HTML, scraping won’t work without authenticated sessions or selenium (browser automation).
You can increase delays (time.sleep) in the code to be more polite.
If you want me to add selenium fallback or help further on authentication or running this more robustly, just let me know!
Args:
reel_url: URL of the Instagram reel to track
output_file: CSV file to store the data
"""
self.reel_url = reel_url
self.output_file = output_file
# User agents to rotate
self.user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:89.0) Gecko/20100101 Firefox/89.0'
]
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('instagram_scraper.log'),
logging.StreamHandler()
]
)
self.logger = logging.getLogger(__name__)
# Initialize CSV file
self._initialize_csv()
# Session for maintaining cookies
self.session = requests.Session()
def _initialize_csv(self):
"""Initialize CSV file with headers if it doesn't exist"""
if not os.path.exists(self.output_file):
with open(self.output_file, 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow([
'timestamp',
'datetime',
'likes_count',
'comments_count',
'views_count',
'status'
])
self.logger.info(f"Created new CSV file: {self.output_file}")
def _get_random_headers(self):
"""Get random headers to avoid detection"""
return {
'User-Agent': random.choice(self.user_agents),
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
}
def _extract_json_data(self, html_content):
"""Extract JSON data from Instagram page"""
try:
# Look for shared data in script tags
pattern = r'window\._sharedData\s*=\s*({.*?});'
match = re.search(pattern, html_content)
if match:
return json.loads(match.group(1))
# Alternative pattern for newer Instagram versions
pattern = r'window\.__additionalDataLoaded\(\'[^\']+\',\s*({.*?})\);'
matches = re.findall(pattern, html_content)
if matches:
return json.loads(matches[0])
return None
except Exception as e:
self.logger.error(f"Error extracting JSON data: {e}")
return None
def _extract_likes_from_html(self, html_content):
"""Extract likes count from HTML using multiple methods"""
try:
soup = BeautifulSoup(html_content, 'html.parser')
# Method 1: Target the exact span with Instagram likes classes
likes_classes = [
'xdj266r', 'x14z9mp', 'xat24cr', 'x1lziwak', 'xexx8yu',
'xyri2b', 'x18d9i69', 'x1c1uobl', 'x1hl2dhg', 'x16tdsg8',
'x1vvkbs'
]
# Look for span with these specific classes
for span in soup.find_all('span', class_=likes_classes):
text = span.get_text().strip()
if re.match(r'^\d+(?:,\d+)*$', text): # Pure number format like "13,572"
likes_count = int(text.replace(',', ''))
self.logger.info(f"Found likes via exact classes: {likes_count}")
return likes_count
# Method 2: Look for spans with any combination of these classes
for span in soup.find_all('span'):
span_classes = span.get('class', [])
# Check if span has at least 3 of our target classes
matching_classes = len([c for c in likes_classes if c in span_classes])
if matching_classes >= 3:
text = span.get_text().strip()
if re.match(r'^\d+(?:,\d+)*$', text):
likes_count = int(text.replace(',', ''))
self.logger.info(f"Found likes via partial class match ({matching_classes} classes): {likes_count}")
return likes_count
# Method 3: Look for any span with comma-separated numbers (Instagram format)
for span in soup.find_all('span'):
text = span.get_text().strip()
if re.match(r'^\d{1,3}(?:,\d{3})*$', text): # Format like 13,572 or 1,234,567
likes_count = int(text.replace(',', ''))
# Only consider it if it's a reasonable likes count (not too small, not too big)
if 1 <= likes_count <= 100000000: # Between 1 and 100M
self.logger.info(f"Found potential likes via number format: {likes_count}")
return likes_count
# Method 4: Use the original long CSS selector
css_selector = "#mount_0_0_pK > div > div > div.x9f619.x1n2onr6.x1ja2u2z > div > div > div.x78zum5.xdt5ytf.x1t2pt76.x1n2onr6.x1ja2u2z.x10cihs4 > div.x9f619.xvbhtw8.x78zum5.x15mokao.x1ga7v0g.x16uus16.xbiv7yw.x1uhb9sk.x1plvlek.xryxfnj.x1c4vz4f.x2lah0s.xdt5ytf.xqjyukv.x1qjc9v5.x1oa3qoh.x1qughib > div.xvc5jky.xh8yej3.x10o80wk.x14k21rp.x17snn68.x6osk4m.x1porb0y.x8vgawa > section > main > div > article > div:nth-child(3) > div > div:nth-child(1) > section.x1e56ztr.x1xmf6yo > div > div > span > a > span > span"
likes_element = soup.select_one(css_selector)
if likes_element:
likes_text = likes_element.get_text().strip()
self.logger.info(f"Found element via CSS selector: '{likes_text}'")
likes_match = re.search(r'(\d+(?:,\d+)*)', likes_text)
if likes_match:
likes_count = int(likes_match.group(1).replace(',', ''))
self.logger.info(f"Extracted likes from CSS selector: {likes_count}")
return likes_count
# Method 5: Search for likes in context (near "like" text)
for element in soup.find_all(['button', 'a', 'div']):
text = element.get_text().lower()
aria_label = element.get('aria-label', '').lower()
if 'like' in text or 'like' in aria_label:
# Look for numbers in this element or nearby elements
for span in element.find_all('span'):
span_text = span.get_text().strip()
if re.match(r'^\d+(?:,\d+)*$', span_text):
likes_count = int(span_text.replace(',', ''))
self.logger.info(f"Found likes near 'like' context: {likes_count}")
return likes_count
# Method 6: Debug - print all spans with numbers
self.logger.info("DEBUG: Looking for all spans with number patterns...")
for span in soup.find_all('span'):
text = span.get_text().strip()
classes = span.get('class', [])
if re.search(r'\d+', text) and len(text) < 20:
self.logger.info(f"DEBUG Span: text='{text}', classes={classes[:5]}...") # Show first 5 classes
self.logger.warning("No likes count found with any method")
return 0
except Exception as e:
self.logger.error(f"Error extracting likes from HTML: {e}")
return 0
def scrape_with_selenium(self):
"""Fallback method using Selenium for JavaScript-heavy content"""
if not SELENIUM_AVAILABLE:
self.logger.error("Selenium not available. Install with: pip install selenium")
return None
try:
# Setup Chrome options
chrome_options = Options()
chrome_options.add_argument('--headless') # Run in background
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--window-size=1920,1080')
chrome_options.add_argument(f'--user-agent={random.choice(self.user_agents)}')
# Initialize driver
driver = webdriver.Chrome(options=chrome_options)
driver.get(self.reel_url)
# Wait for page to load
time.sleep(5)
# Try multiple selectors for likes
likes_selectors = [
'button span span', # Common likes button
'[aria-label*="like"] span',
'span[class*="_ac2a"]',
'span:contains("like")',
'button[aria-label*="like"]',
]
likes_count = 0
for selector in likes_selectors:
try:
if 'contains' in selector:
# Use XPath for contains
xpath = f"//span[contains(text(), 'like')]"
elements = driver.find_elements(By.XPATH, xpath)
else:
elements = driver.find_elements(By.CSS_SELECTOR, selector)
for element in elements:
text = element.text.strip()
aria_label = element.get_attribute('aria-label') or ''
# Look for numbers in text or aria-label
for content in [text, aria_label]:
if content and 'like' in content.lower():
match = re.search(r'(\d+(?:,\d+)*)', content)
if match:
likes_count = int(match.group(1).replace(',', ''))
self.logger.info(f"Selenium found likes: {likes_count}")
driver.quit()
return likes_count
except Exception as e:
continue
# If no likes found, get page source for debugging
page_source = driver.page_source
with open('selenium_debug.html', 'w', encoding='utf-8') as f:
f.write(page_source)
self.logger.info("Selenium page source saved to selenium_debug.html")
driver.quit()
return 0
except Exception as e:
self.logger.error(f"Selenium scraping failed: {e}")
return None
def scrape_reel_data(self):
"""Scrape reel data from Instagram"""
try:
headers = self._get_random_headers()
# Add random delay to avoid rate limiting
time.sleep(random.uniform(2, 5))
response = self.session.get(self.reel_url, headers=headers, timeout=30)
response.raise_for_status()
html_content = response.text
self.logger.info(f"Page loaded successfully, content length: {len(html_content)}")
# Save HTML content for debugging (optional)
# with open('debug_page.html', 'w', encoding='utf-8') as f:
# f.write(html_content)
# Extract JSON data
json_data = self._extract_json_data(html_content)
likes_count = 0
comments_count = 0
views_count = 0
if json_data:
try:
# Navigate through JSON structure to find post data
entry_data = json_data.get('entry_data', {})
post_page = entry_data.get('PostPage', [])
if post_page and len(post_page) > 0:
media = post_page[0].get('graphql', {}).get('shortcode_media', {})
likes_count = media.get('edge_media_preview_like', {}).get('count', 0)
comments_count = media.get('edge_media_to_comment', {}).get('count', 0)
views_count = media.get('video_view_count', 0)
self.logger.info(f"Extracted from JSON - Likes: {likes_count}, Comments: {comments_count}")
except Exception as e:
self.logger.warning(f"JSON parsing failed, falling back to HTML parsing: {e}")
# Always try HTML parsing (prioritize it)
html_likes = self._extract_likes_from_html(html_content)
if html_likes > 0:
likes_count = html_likes
self.logger.info(f"Using HTML extracted likes: {likes_count}")
elif likes_count == 0:
self.logger.warning("No likes found in HTML, trying Selenium...")
# Try Selenium as fallback
selenium_likes = self.scrape_with_selenium()
if selenium_likes and selenium_likes > 0:
likes_count = selenium_likes
self.logger.info(f"Using Selenium extracted likes: {likes_count}")
else:
self.logger.warning("No likes found in either HTML or Selenium")
return {
'likes_count': likes_count,
'comments_count': comments_count,
'views_count': views_count,
'status': 'success'
}
except requests.exceptions.RequestException as e:
self.logger.error(f"Request failed: {e}")
return {
'likes_count': 0,
'comments_count': 0,
'views_count': 0,
'status': f'request_error: {str(e)}'
}
except Exception as e:
self.logger.error(f"Scraping failed: {e}")
return {
'likes_count': 0,
'comments_count': 0,
'views_count': 0,
'status': f'error: {str(e)}'
}
def save_data_point(self, data):
"""Save a data point to CSV file"""
timestamp = time.time()
datetime_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
row_data = [
timestamp,
datetime_str,
data['likes_count'],
data['comments_count'],
data['views_count'],
data['status']
]
try:
with open(self.output_file, 'a', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(row_data)
self.logger.info(f"Data saved: {datetime_str} - Likes: {data['likes_count']}")
except Exception as e:
self.logger.error(f"Failed to save data: {e}")
def track_likes(self, duration_hours=24, interval_minutes=5):
"""
Track likes for specified duration
Args:
duration_hours: How long to track (in hours)
interval_minutes: Interval between checks (in minutes)
"""
interval_seconds = interval_minutes * 60
total_iterations = (duration_hours * 3600) // interval_seconds
self.logger.info(f"Starting tracking for {duration_hours} hours with {interval_minutes}-minute intervals")
self.logger.info(f"Total iterations planned: {total_iterations}")
for i in range(total_iterations):
try:
self.logger.info(f"Iteration {i+1}/{total_iterations}")
# Scrape data
data = self.scrape_reel_data()
# Save data
self.save_data_point(data)
# Wait for next iteration (except for the last one)
if i < total_iterations - 1:
self.logger.info(f"Waiting {interval_minutes} minutes until next check...")
time.sleep(interval_seconds)
except KeyboardInterrupt:
self.logger.info("Tracking stopped by user")
break
except Exception as e:
self.logger.error(f"Error in iteration {i+1}: {e}")
# Continue with next iteration after a short delay
time.sleep(30)
self.logger.info("Tracking completed!")
# Create tracker instance
tracker = InstagramLikesScraper(REEL_URL)
# Start tracking for 24 hours, checking every 5 minutes
tracker.track_likes(duration_hours=24, interval_minutes=5)
print(f"Data saved to: {tracker.output_file}") this code is working fien
import streamlit as st
import threading
import time
import pandas as pd
# Paste your entire InstagramLikesScraper class here, unchanged
import requests
import csv
import json
import re
from datetime import datetime
import logging
import os
from bs4 import BeautifulSoup
import random
from urllib.parse import quote
# Try to import selenium for browser automation fallback
try:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
SELENIUM_AVAILABLE = True
except ImportError:
SELENIUM_AVAILABLE = False
class InstagramLikesScraper:
def __init__(self, reel_url: str, output_file: str = 'instagram_likes_data.csv'):
self.reel_url = reel_url
self.output_file = output_file
self.user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:89.0) Gecko/20100101 Firefox/89.0'
]
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[logging.FileHandler('instagram_scraper.log'), logging.StreamHandler()]
)
self.logger = logging.getLogger(__name__)
self._initialize_csv()
self.session = requests.Session()
def _initialize_csv(self):
if not os.path.exists(self.output_file):
with open(self.output_file, 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(['timestamp','datetime','likes_count','comments_count','views_count','status'])
self.logger.info(f"Created new CSV file: {self.output_file}")
def _get_random_headers(self):
return {
'User-Agent': random.choice(self.user_agents),
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
}
def _extract_json_data(self, html_content):
try:
pattern = r'window\._sharedData\s*=\s*({.*?});'
match = re.search(pattern, html_content)
if match:
return json.loads(match.group(1))
pattern = r'window\.__additionalDataLoaded\(\'[^\']+\',\s*({.*?})\);'
matches = re.findall(pattern, html_content)
if matches:
return json.loads(matches[0])
return None
except Exception as e:
self.logger.error(f"Error extracting JSON data: {e}")
return None
def _extract_likes_from_html(self, html_content):
try:
soup = BeautifulSoup(html_content, 'html.parser')
for span in soup.find_all('span'):
text = span.get_text().strip()
if re.match(r'^\d{1,3}(?:,\d{3})*$', text):
likes = int(text.replace(',', ''))
if 1 <= likes <= 100_000_000:
return likes
return 0
except Exception as e:
self.logger.error(f"Error extracting likes from HTML: {e}")
return 0
def scrape_reel_data(self):
try:
headers = self._get_random_headers()
time.sleep(random.uniform(2, 5))
response = self.session.get(self.reel_url, headers=headers, timeout=30)
response.raise_for_status()
html_content = response.text
json_data = self._extract_json_data(html_content)
likes_count = 0
comments_count = 0
views_count = 0
if json_data:
try:
entry_data = json_data.get('entry_data', {})
post_page = entry_data.get('PostPage', [])
if post_page and len(post_page) > 0:
media = post_page[0].get('graphql', {}).get('shortcode_media', {})
likes_count = media.get('edge_media_preview_like', {}).get('count', 0)
comments_count = media.get('edge_media_to_comment', {}).get('count', 0)
views_count = media.get('video_view_count', 0)
except Exception as e:
self.logger.warning(f"JSON parsing failed, falling back: {e}")
html_likes = self._extract_likes_from_html(html_content)
if html_likes > 0:
likes_count = html_likes
return {
'likes_count': likes_count,
'comments_count': comments_count,
'views_count': views_count,
'status': 'success'
}
except Exception as e:
self.logger.error(f"Scraping failed: {e}")
return {
'likes_count': 0,
'comments_count': 0,
'views_count': 0,
'status': f'error: {str(e)}'
}
def save_data_point(self, data):
timestamp = time.time()
datetime_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
row = [timestamp, datetime_str, data['likes_count'], data['comments_count'], data['views_count'], data['status']]
try:
with open(self.output_file, 'a', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(row)
self.logger.info(f"Saved data point: {datetime_str} Likes:{data['likes_count']}")
except Exception as e:
self.logger.error(f"Failed saving data: {e}")
# Streamlit app tracking logic
if 'tracker' not in st.session_state:
st.session_state.tracker = None
if 'tracking' not in st.session_state:
st.session_state.tracking = False
if 'data' not in st.session_state:
st.session_state.data = []
def scraper_thread_func(url, dur_hours, interval_min):
st.session_state.tracking = True
st.session_state.data.clear()
scraper = InstagramLikesScraper(url)
iters = int(dur_hours*60//interval_min)
for i in range(iters):
if not st.session_state.tracking:
break
res = scraper.scrape_reel_data()
scraper.save_data_point(res)
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
record = {
'datetime': now,
**res
}
st.session_state.data.append(record)
time.sleep(interval_min*60)
st.session_state.tracking = False
st.title("Instagram Reel Likes Tracker")
with st.form("track_form"):
url = st.text_input("Instagram Reel URL", value="", placeholder="https://www.instagram.com/reel/xxxxxx/")
dur = st.number_input("Duration (hours)", min_value=0.1, value=0.1, step=0.1)
interval = st.number_input("Interval (minutes)", min_value=0.1, value=1.0, step=0.1)
submit = st.form_submit_button("Start Tracking")
if submit:
if url.strip() == "":
st.error("Please enter a valid Instagram reel URL")
elif st.session_state.tracking:
st.warning("Tracking already in progress")
else:
thread = threading.Thread(target=scraper_thread_func, args=(url, dur, interval), daemon=True)
thread.start()
st.success("Started tracking...")
st.write(f"Tracking status: {'Active' if st.session_state.tracking else 'Stopped'}")
if st.session_state.data:
df = pd.DataFrame(st.session_state.data)
st.dataframe(df[['datetime', 'likes_count', 'comments_count', 'views_count', 'status']])
if st.session_state.tracking:
if st.button("Stop Tracking"):
st.session_state.tracking = False
st.success("Tracking stopped by user")
if st.session_state.data:
csv_data = pd.DataFrame(st.session_state.data).to_csv(index=False).encode('utf-8')
st.download_button("Download CSV", data=csv_data, file_name="likes_data.csv", mime="text/csv")
How to use this:
Paste your full working class exactly (as above).
Run streamlit run streamlit_instagram_tracker.py
Enter your Instagram reel URL, duration, interval
Click Start Tracking — data will be fetched in background every interval minutes until duration hours have passed or until you press Stop Tracking.
Live results show in table.
Download CSV button appears once data exists.
Important notes:
Instagram scraping can be flaky — sometimes zero if Instagram blocks requests or requires authentication.
Your original class’s selenium fallback is not included here, but you can add it similarly in the class.
Streamlit UI updates when state changes, but the table redraw relies on user interaction or reruns. You can add st.experimental_rerun() or st_autorefresh for auto-refresh if you want.
If you want help adding selenium fallback or improving robustness let me know!
def scraper_thread_func(url, dur_hours, interval_min):
global tracking_flag
tracking_flag = True
with data_lock:
scraped_data.clear()
scraper = InstagramLikesScraper(url)
iters = int(dur_hours * 60 // interval_min)
for i in range(iters):
if not tracking_flag:
break
res = scraper.scrape_reel_data()
scraper.save_data_point(res)
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
record = {'datetime': now, **res}
with data_lock:
scraped_data.append(record)
time.sleep(interval_min * 60)
tracking_flag = False
And then in your main Streamlit app, inside the main script (not thread), read the data safely:
python
if tracking_flag:
if st.button("Stop Tracking"):
tracking_flag = False
st.success("Tracking stopped by user")
with data_lock:
data_to_show = scraped_data.copy() # shallow copy to avoid concurrency issues
if data_to_show:
df = pd.DataFrame(data_to_show)
st.dataframe(df[['datetime', 'likes_count', 'comments_count', 'views_count', 'status']])
Option 2: Use libraries like streamlit-webrtc, st.experimental_data_editor(), or async alternatives
Streamlit itself recommends avoiding shared mutable session state across threads.
For complex or long-running background processing, use task queues (Celery, RQ) or a database/message broker.
Then Streamlit can poll periodically from that external source.
Minimal code fix applied to your example
Here’s a full fixed minimal working example showing how you can handle shared data between thread and Streamlit main app without touching st.session_state inside the thread.
python
import streamlit as st
import threading
import time
import pandas as pd
from datetime import datetime
# Your InstagramLikesScraper class goes here (unchanged)
# -- paste your full class code here --
# Shared data and synchronization lock
scraped_data = []
data_lock = threading.Lock()
tracking_flag = False
def scraper_thread_func(url, dur_hours, interval_min):
global tracking_flag
tracking_flag = True
with data_lock:
scraped_data.clear()
scraper = InstagramLikesScraper(url)
iters = int(dur_hours * 60 // interval_min)
for _ in range(iters):
if not tracking_flag:
break
res = scraper.scrape_reel_data()
scraper.save_data_point(res)
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
record = {'datetime': now, **res}
with data_lock:
scraped_data.append(record)
time.sleep(interval_min * 60)
tracking_flag = False
st.title("Instagram Reel Likes Tracker (Threadsafe Example)")
url = st.text_input("Instagram Reel URL", placeholder="https://www.instagram.com/reel/xxxxxx/")
dur = st.number_input("Duration (hours)", min_value=0.1, value=0.1, step=0.1)
interval = st.number_input("Interval (minutes)", min_value=0.1, value=1.0, step=0.1)
start_clicked = st.button("Start Tracking")
stop_clicked = st.button("Stop Tracking")
if start_clicked and not tracking_flag:
thread = threading.Thread(target=scraper_thread_func, args=(url, dur, interval), daemon=True)
thread.start()
st.success("Started tracking!")
if stop_clicked and tracking_flag:
tracking_flag = False
st.warning("Stopping tracking...")
st.write(f"Tracking Status: {'Active' if tracking_flag else 'Stopped'}")
with data_lock:
data_for_display = scraped_data.copy()
if data_for_display:
df = pd.DataFrame(data_for_display)
st.dataframe(df[['datetime', 'likes_count', 'comments_count', 'views_count', 'status']])
if data_for_display:
csv_data = pd.DataFrame(data_for_display).to_csv(index=False).encode('utf-8')
st.download_button("Download CSV", data=csv_data, file_name="likes_data.csv", mime="text/csv")
Summary
Never access or modify st.session_state inside background threads.
Instead, keep your own thread-safe shared variables (list + Lock).
Read shared data only inside the main Streamlit thread (the main script), e.g. before calling display functions.
Use polling, button clicks, or st.experimental_rerun() to update UI if you want auto-refresh.
If you want, I can help you prepare a complete file with your full scraper and this threading fix applied — just ask!
import streamlit as st
import threading
import time
import csv
import json
import re
from datetime import datetime
import logging
import os
from bs4 import BeautifulSoup
import random
import requests
from urllib.parse import quote
import pandas as pd
# Try to import selenium if needed (optional)
try:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
SELENIUM_AVAILABLE = True
except ImportError:
SELENIUM_AVAILABLE = False
class InstagramLikesScraper:
def __init__(self, reel_url: str, output_file: str = 'instagram_likes_data.csv'):
self.reel_url = reel_url
self.output_file = output_file
self.user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:89.0) Gecko/20100101 Firefox/89.0',
]
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[logging.FileHandler('instagram_scraper.log'), logging.StreamHandler()]
)
self.logger = logging.getLogger(__name__)
self._initialize_csv()
self.session = requests.Session()
def _initialize_csv(self):
if not os.path.exists(self.output_file):
with open(self.output_file, 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(['timestamp', 'datetime', 'likes_count', 'comments_count', 'views_count', 'status'])
self.logger.info(f"Created new CSV file: {self.output_file}")
def _get_random_headers(self):
return {
'User-Agent': random.choice(self.user_agents),
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
}
def _extract_json_data(self, html_content):
try:
pattern = r'window\._sharedData\s*=\s*({.*?});'
match = re.search(pattern, html_content)
if match:
return json.loads(match.group(1))
pattern = r'window\.__additionalDataLoaded\(\'[^\']+\',\s*({.*?})\);'
matches = re.findall(pattern, html_content)
if matches:
return json.loads(matches[0])
return None
except Exception as e:
self.logger.error(f"Error extracting JSON data: {e}")
return None
def _extract_likes_from_html(self, html_content):
try:
soup = BeautifulSoup(html_content, 'html.parser')
for span in soup.find_all('span'):
text = span.get_text().strip()
if re.match(r'^\d{1,3}(?:,\d{3})*$', text):
likes = int(text.replace(',', ''))
if 1 <= likes <= 100_000_000:
return likes
return 0
except Exception as e:
self.logger.error(f"Error extracting likes from HTML: {e}")
return 0
def scrape_reel_data(self):
try:
headers = self._get_random_headers()
time.sleep(random.uniform(2, 5))
response = self.session.get(self.reel_url, headers=headers, timeout=30)
response.raise_for_status()
html_content = response.text
json_data = self._extract_json_data(html_content)
likes_count = 0
comments_count = 0
views_count = 0
if json_data:
try:
entry_data = json_data.get('entry_data', {})
post_page = entry_data.get('PostPage', [])
if post_page and len(post_page) > 0:
media = post_page[0].get('graphql', {}).get('shortcode_media', {})
likes_count = media.get('edge_media_preview_like', {}).get('count', 0)
comments_count = media.get('edge_media_to_comment', {}).get('count', 0)
views_count = media.get('video_view_count', 0)
except Exception as e:
self.logger.warning(f"JSON parsing failed, falling back: {e}")
html_likes = self._extract_likes_from_html(html_content)
if html_likes > 0:
likes_count = html_likes
return {
'likes_count': likes_count,
'comments_count': comments_count,
'views_count': views_count,
'status': 'success',
}
except Exception as e:
self.logger.error(f"Scraping failed: {e}")
return {'likes_count': 0, 'comments_count': 0, 'views_count': 0, 'status': f'error: {str(e)}'}
def save_data_point(self, data):
timestamp = time.time()
datetime_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
row = [timestamp, datetime_str, data['likes_count'], data['comments_count'], data['views_count'], data['status']]
try:
with open(self.output_file, 'a', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(row)
self.logger.info(f"Saved data point: {datetime_str} Likes:{data['likes_count']}")
except Exception as e:
self.logger.error(f"Failed saving data: {e}")
# Global shared data (thread-safe)
scraped_data = []
data_lock = threading.Lock()
tracking_flag = False
def scraper_thread_func(url, dur_hours, interval_min):
global tracking_flag
tracking_flag = True
with data_lock:
scraped_data.clear()
scraper = InstagramLikesScraper(url)
iters = int(dur_hours * 60 // interval_min)
for _ in range(iters):
if not tracking_flag:
break
res = scraper.scrape_reel_data()
scraper.save_data_point(res)
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
record = {'datetime': now, **res}
with data_lock:
scraped_data.append(record)
time.sleep(interval_min * 60)
tracking_flag = False
st.title("Instagram Reel Likes Tracker")
url = st.text_input("Instagram Reel URL", placeholder="https://www.instagram.com/reel/xxxxxx/")
dur = st.number_input("Duration (hours)", min_value=0.1, value=0.5, step=0.1)
interval = st.number_input("Interval (minutes)", min_value=0.1, value=1.0, step=0.1)
start_clicked = st.button("Start Tracking")
stop_clicked = st.button("Stop Tracking")
if start_clicked:
if not url.strip():
st.error("Please enter a valid Instagram reel URL")
elif tracking_flag:
st.warning("Tracking already in progress")
else:
thread = threading.Thread(target=scraper_thread_func, args=(url, dur, interval), daemon=True)
thread.start()
st.success("Started tracking!")
if stop_clicked:
if tracking_flag:
tracking_flag = False
st.warning("Tracking stopping...")
else:
st.info("Tracking is not running.")
st.write(f"Tracking Status: {'Active' if tracking_flag else 'Stopped'}")
with data_lock:
data_for_display = scraped_data.copy()
if data_for_display:
df = pd.DataFrame(data_for_display)
st.dataframe(df[['datetime', 'likes_count', 'comments_count', 'views_count', 'status']])
if data_for_display:
csv_data = pd.DataFrame(data_for_display).to_csv(index=False).encode('utf-8')
st.download_button("Download CSV", data=csv_data, file_name="likes_data.csv", mime="text/csv")
What it does:
Runs your scraper class in a separate thread.
Uses a thread-safe global list with a lock to store and read scraped results.
UI lets you start/stop tracking, shows live status and data.
Export results to CSV.
Avoids st.session_state inside threads, preventing errors you saw.
Feel free to ask if you'd like selenium fallback reintegrated or UI enhancements!
Next steps:
Replace your current _extract_likes_from_html method with this.
Run scraping again.
If still zero, most likely Instagram is not serving detailed page HTML without login or via this request method.
Alternative: Use Selenium fallback for JS-rendered content
If you can use Selenium (ChromeDriver) for the fallback scraping (which your original class has), it will render JS and get actual likes.
Ensure:
selenium Python package installed
ChromeDriver installed and on PATH or specify executable path in code
Your original scrape_with_selenium() method looks good.
If you want, I can help you integrate Selenium fallback into your Thread-Safe Streamlit app so the scraper tries normal requests first, then Selenium if zero likes found.
TL;DR – what you can do now:
Replace _extract_likes_from_html with the above CSS selector enhanced version.
Use Selenium fallback if this fails.
Consider logged-in scraping or official API if possible (to avoid blocks/errors).
If you'd like, I can provide the exact updated full Streamlit-ready code with CSS selector method + Selenium fallback integrated — just ask!
Args:
reel_url: URL of the Instagram reel to track
output_file: CSV file to store the data
"""
self.reel_url = reel_url
self.output_file = output_file
# User agents to rotate
self.user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:89.0) Gecko/20100101 Firefox/89.0'
]
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('instagram_scraper.log'),
logging.StreamHandler()
]
)
self.logger = logging.getLogger(__name__)
# Initialize CSV file
self._initialize_csv()
# Session for maintaining cookies
self.session = requests.Session()
def _initialize_csv(self):
"""Initialize CSV file with headers if it doesn't exist"""
if not os.path.exists(self.output_file):
with open(self.output_file, 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow([
'timestamp',
'datetime',
'likes_count',
'comments_count',
'views_count',
'status'
])
self.logger.info(f"Created new CSV file: {self.output_file}")
def _get_random_headers(self):
"""Get random headers to avoid detection"""
return {
'User-Agent': random.choice(self.user_agents),
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
}
def _extract_json_data(self, html_content):
"""Extract JSON data from Instagram page"""
try:
# Look for shared data in script tags
pattern = r'window\._sharedData\s*=\s*({.*?});'
match = re.search(pattern, html_content)
if match:
return json.loads(match.group(1))
# Alternative pattern for newer Instagram versions
pattern = r'window\.__additionalDataLoaded\(\'[^\']+\',\s*({.*?})\);'
matches = re.findall(pattern, html_content)
if matches:
return json.loads(matches[0])
return None
except Exception as e:
self.logger.error(f"Error extracting JSON data: {e}")
return None
def _extract_likes_from_html(self, html_content):
"""Extract likes count from HTML using multiple methods"""
try:
soup = BeautifulSoup(html_content, 'html.parser')
# Method 1: Target the exact span with Instagram likes classes
likes_classes = [
'xdj266r', 'x14z9mp', 'xat24cr', 'x1lziwak', 'xexx8yu',
'xyri2b', 'x18d9i69', 'x1c1uobl', 'x1hl2dhg', 'x16tdsg8',
'x1vvkbs'
]
# Look for span with these specific classes
for span in soup.find_all('span', class_=likes_classes):
text = span.get_text().strip()
if re.match(r'^\d+(?:,\d+)*$', text): # Pure number format like "13,572"
likes_count = int(text.replace(',', ''))
self.logger.info(f"Found likes via exact classes: {likes_count}")
return likes_count
# Method 2: Look for spans with any combination of these classes
for span in soup.find_all('span'):
span_classes = span.get('class', [])
# Check if span has at least 3 of our target classes
matching_classes = len([c for c in likes_classes if c in span_classes])
if matching_classes >= 3:
text = span.get_text().strip()
if re.match(r'^\d+(?:,\d+)*$', text):
likes_count = int(text.replace(',', ''))
self.logger.info(f"Found likes via partial class match ({matching_classes} classes): {likes_count}")
return likes_count
# Method 3: Look for any span with comma-separated numbers (Instagram format)
for span in soup.find_all('span'):
text = span.get_text().strip()
if re.match(r'^\d{1,3}(?:,\d{3})*$', text): # Format like 13,572 or 1,234,567
likes_count = int(text.replace(',', ''))
# Only consider it if it's a reasonable likes count (not too small, not too big)
if 1 <= likes_count <= 100000000: # Between 1 and 100M
self.logger.info(f"Found potential likes via number format: {likes_count}")
return likes_count
# Method 4: Use the original long CSS selector
css_selector = "#mount_0_0_pK > div > div > div.x9f619.x1n2onr6.x1ja2u2z > div > div > div.x78zum5.xdt5ytf.x1t2pt76.x1n2onr6.x1ja2u2z.x10cihs4 > div.x9f619.xvbhtw8.x78zum5.x15mokao.x1ga7v0g.x16uus16.xbiv7yw.x1uhb9sk.x1plvlek.xryxfnj.x1c4vz4f.x2lah0s.xdt5ytf.xqjyukv.x1qjc9v5.x1oa3qoh.x1qughib > div.xvc5jky.xh8yej3.x10o80wk.x14k21rp.x17snn68.x6osk4m.x1porb0y.x8vgawa > section > main > div > article > div:nth-child(3) > div > div:nth-child(1) > section.x1e56ztr.x1xmf6yo > div > div > span > a > span > span"
likes_element = soup.select_one(css_selector)
if likes_element:
likes_text = likes_element.get_text().strip()
self.logger.info(f"Found element via CSS selector: '{likes_text}'")
likes_match = re.search(r'(\d+(?:,\d+)*)', likes_text)
if likes_match:
likes_count = int(likes_match.group(1).replace(',', ''))
self.logger.info(f"Extracted likes from CSS selector: {likes_count}")
return likes_count
# Method 5: Search for likes in context (near "like" text)
for element in soup.find_all(['button', 'a', 'div']):
text = element.get_text().lower()
aria_label = element.get('aria-label', '').lower()
if 'like' in text or 'like' in aria_label:
# Look for numbers in this element or nearby elements
for span in element.find_all('span'):
span_text = span.get_text().strip()
if re.match(r'^\d+(?:,\d+)*$', span_text):
likes_count = int(span_text.replace(',', ''))
self.logger.info(f"Found likes near 'like' context: {likes_count}")
return likes_count
# Method 6: Debug - print all spans with numbers
self.logger.info("DEBUG: Looking for all spans with number patterns...")
for span in soup.find_all('span'):
text = span.get_text().strip()
classes = span.get('class', [])
if re.search(r'\d+', text) and len(text) < 20:
self.logger.info(f"DEBUG Span: text='{text}', classes={classes[:5]}...") # Show first 5 classes
self.logger.warning("No likes count found with any method")
return 0
except Exception as e:
self.logger.error(f"Error extracting likes from HTML: {e}")
return 0
def scrape_with_selenium(self):
"""Fallback method using Selenium for JavaScript-heavy content"""
if not SELENIUM_AVAILABLE:
self.logger.error("Selenium not available. Install with: pip install selenium")
return None
try:
# Setup Chrome options
chrome_options = Options()
chrome_options.add_argument('--headless') # Run in background
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--window-size=1920,1080')
chrome_options.add_argument(f'--user-agent={random.choice(self.user_agents)}')
# Initialize driver
driver = webdriver.Chrome(options=chrome_options)
driver.get(self.reel_url)
# Wait for page to load
time.sleep(5)
# Try multiple selectors for likes
likes_selectors = [
'button span span', # Common likes button
'[aria-label*="like"] span',
'span[class*="_ac2a"]',
'span:contains("like")',
'button[aria-label*="like"]',
]
likes_count = 0
for selector in likes_selectors:
try:
if 'contains' in selector:
# Use XPath for contains
xpath = f"//span[contains(text(), 'like')]"
elements = driver.find_elements(By.XPATH, xpath)
else:
elements = driver.find_elements(By.CSS_SELECTOR, selector)
for element in elements:
text = element.text.strip()
aria_label = element.get_attribute('aria-label') or ''
# Look for numbers in text or aria-label
for content in [text, aria_label]:
if content and 'like' in content.lower():
match = re.search(r'(\d+(?:,\d+)*)', content)
if match:
likes_count = int(match.group(1).replace(',', ''))
self.logger.info(f"Selenium found likes: {likes_count}")
driver.quit()
return likes_count
except Exception as e:
continue
# If no likes found, get page source for debugging
page_source = driver.page_source
with open('selenium_debug.html', 'w', encoding='utf-8') as f:
f.write(page_source)
self.logger.info("Selenium page source saved to selenium_debug.html")
driver.quit()
return 0
except Exception as e:
self.logger.error(f"Selenium scraping failed: {e}")
return None
def scrape_reel_data(self):
"""Scrape reel data from Instagram"""
try:
headers = self._get_random_headers()
# Add random delay to avoid rate limiting
time.sleep(random.uniform(2, 5))
response = self.session.get(self.reel_url, headers=headers, timeout=30)
response.raise_for_status()
html_content = response.text
self.logger.info(f"Page loaded successfully, content length: {len(html_content)}")
# Save HTML content for debugging (optional)
# with open('debug_page.html', 'w', encoding='utf-8') as f:
# f.write(html_content)
# Extract JSON data
json_data = self._extract_json_data(html_content)
likes_count = 0
comments_count = 0
views_count = 0
if json_data:
try:
# Navigate through JSON structure to find post data
entry_data = json_data.get('entry_data', {})
post_page = entry_data.get('PostPage', [])
if post_page and len(post_page) > 0:
media = post_page[0].get('graphql', {}).get('shortcode_media', {})
likes_count = media.get('edge_media_preview_like', {}).get('count', 0)
comments_count = media.get('edge_media_to_comment', {}).get('count', 0)
views_count = media.get('video_view_count', 0)
self.logger.info(f"Extracted from JSON - Likes: {likes_count}, Comments: {comments_count}")
except Exception as e:
self.logger.warning(f"JSON parsing failed, falling back to HTML parsing: {e}")
# Always try HTML parsing (prioritize it)
html_likes = self._extract_likes_from_html(html_content)
if html_likes > 0:
likes_count = html_likes
self.logger.info(f"Using HTML extracted likes: {likes_count}")
elif likes_count == 0:
self.logger.warning("No likes found in HTML, trying Selenium...")
# Try Selenium as fallback
selenium_likes = self.scrape_with_selenium()
if selenium_likes and selenium_likes > 0:
likes_count = selenium_likes
self.logger.info(f"Using Selenium extracted likes: {likes_count}")
else:
self.logger.warning("No likes found in either HTML or Selenium")
return {
'likes_count': likes_count,
'comments_count': comments_count,
'views_count': views_count,
'status': 'success'
}
except requests.exceptions.RequestException as e:
self.logger.error(f"Request failed: {e}")
return {
'likes_count': 0,
'comments_count': 0,
'views_count': 0,
'status': f'request_error: {str(e)}'
}
except Exception as e:
self.logger.error(f"Scraping failed: {e}")
return {
'likes_count': 0,
'comments_count': 0,
'views_count': 0,
'status': f'error: {str(e)}'
}
def save_data_point(self, data):
"""Save a data point to CSV file"""
timestamp = time.time()
datetime_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
row_data = [
timestamp,
datetime_str,
data['likes_count'],
data['comments_count'],
data['views_count'],
data['status']
]
try:
with open(self.output_file, 'a', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(row_data)
self.logger.info(f"Data saved: {datetime_str} - Likes: {data['likes_count']}")
except Exception as e:
self.logger.error(f"Failed to save data: {e}")
def track_likes(self, duration_hours=24, interval_minutes=5):
"""
Track likes for specified duration
Args:
duration_hours: How long to track (in hours)
interval_minutes: Interval between checks (in minutes)
"""
interval_seconds = interval_minutes * 60
total_iterations = (duration_hours * 3600) // interval_seconds
self.logger.info(f"Starting tracking for {duration_hours} hours with {interval_minutes}-minute intervals")
self.logger.info(f"Total iterations planned: {total_iterations}")
for i in range(total_iterations):
try:
self.logger.info(f"Iteration {i+1}/{total_iterations}")
# Scrape data
data = self.scrape_reel_data()
# Save data
self.save_data_point(data)
# Wait for next iteration (except for the last one)
if i < total_iterations - 1:
self.logger.info(f"Waiting {interval_minutes} minutes until next check...")
time.sleep(interval_seconds)
except KeyboardInterrupt:
self.logger.info("Tracking stopped by user")
break
except Exception as e:
self.logger.error(f"Error in iteration {i+1}: {e}")
# Continue with next iteration after a short delay
time.sleep(30)
self.logger.info("Tracking completed!")
# Create tracker instance
tracker = InstagramLikesScraper(REEL_URL)
# Start tracking for 24 hours, checking every 5 minutes
tracker.track_likes(duration_hours=24, interval_minutes=5)
print(f"Data saved to: {tracker.output_file}") so use this selenium'
import streamlit as st
import threading
import time
import csv
import json
import re
from datetime import datetime
import logging
import os
from bs4 import BeautifulSoup
import random
import requests
from urllib.parse import quote
import pandas as pd
# Selenium imports and availability
try:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
SELENIUM_AVAILABLE = True
except ImportError:
SELENIUM_AVAILABLE = False
class InstagramLikesScraper:
def __init__(self, reel_url: str, output_file: str = 'instagram_likes_data.csv'):
self.reel_url = reel_url
self.output_file = output_file
self.user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:89.0) Gecko/20100101 Firefox/89.0'
]
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[logging.FileHandler('instagram_scraper.log'), logging.StreamHandler()]
)
self.logger = logging.getLogger(__name__)
self._initialize_csv()
self.session = requests.Session()
def _initialize_csv(self):
if not os.path.exists(self.output_file):
with open(self.output_file, 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(['timestamp', 'datetime', 'likes_count', 'comments_count', 'views_count', 'status'])
self.logger.info(f"Created new CSV file: {self.output_file}")
def _get_random_headers(self):
return {
'User-Agent': random.choice(self.user_agents),
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
}
def _extract_json_data(self, html_content):
try:
pattern = r'window\._sharedData\s*=\s*({.*?});'
match = re.search(pattern, html_content)
if match:
return json.loads(match.group(1))
pattern = r'window\.__additionalDataLoaded\(\'[^\']+\',\s*({.*?})\);'
matches = re.findall(pattern, html_content)
if matches:
return json.loads(matches[0])
return None
except Exception as e:
self.logger.error(f"Error extracting JSON data: {e}")
return None
def _extract_likes_from_html(self, html_content):
try:
soup = BeautifulSoup(html_content, 'html.parser')
# CSS selector fallback (your provided one)
css_selector = "#mount_0_0_pK > div > div > div.x9f619.x1n2onr6.x1ja2u2z > div > div > div.x78zum5.xdt5ytf.x1t2pt76.x1n2onr6.x1ja2u2z.x10cihs4 > div.x9f619.xvbhtw8.x78zum5.x15mokao.x1ga7v0g.x16uus16.xbiv7yw.x1uhb9sk.x1plvlek.xryxfnj.x1c4vz4f.x2lah0s.xdt5ytf.xqjyukv.x1qjc9v5.x1oa3qoh.x1qughib > div.xvc5jky.xh8yej3.x10o80wk.x14k21rp.x17snn68.x6osk4m.x1porb0y.x8vgawa > section > main > div > article > div:nth-child(3) > div > div:nth-child(1) > section.x1e56ztr.x1xmf6yo > div > div > span > a > span > span"
likes_element = soup.select_one(css_selector)
if likes_element:
likes_text = likes_element.get_text().strip()
if likes_text:
likes_number = int(likes_text.replace(',', ''))
self.logger.info(f"Likes found via CSS selector: {likes_number}")
return likes_number
# fallback to any numeric span
for span in soup.find_all('span'):
text = span.get_text().strip()
if re.match(r'^\d{1,3}(?:,\d{3})*$', text):
likes = int(text.replace(',', ''))
if 1 <= likes <= 100_000_000:
self.logger.info(f"Likes found via span text: {likes}")
return likes
return 0
except Exception as e:
self.logger.error(f"Error extracting likes: {e}")
return 0
def scrape_with_selenium(self):
if not SELENIUM_AVAILABLE:
self.logger.error("Selenium not installed. Install with: pip install selenium")
return None
try:
options = Options()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--window-size=1920,1080')
user_agent = random.choice(self.user_agents)
options.add_argument(f'--user-agent={user_agent}')
driver = webdriver.Chrome(options=options)
driver.get(self.reel_url)
time.sleep(5) # wait for JS
potential_selectors = [
'button span span',
'[aria-label*="like"] span',
'span[class*="_ac2a"]',
'button[aria-label*="like"]',
]
for selector in potential_selectors:
try:
if 'contains' in selector:
xpath = "//span[contains(text(), 'like')]"
elements = driver.find_elements(By.XPATH, xpath)
else:
elements = driver.find_elements(By.CSS_SELECTOR, selector)
for elem in elements:
text = elem.text.strip()
aria_label = elem.get_attribute('aria-label') or ''
for content in [text, aria_label]:
if content and 'like' in content.lower():
match = re.search(r'(\d+(?:,\d+)*)', content)
if match:
count = int(match.group(1).replace(',', ''))
self.logger.info(f"Selenium found likes: {count}")
driver.quit()
return count
except Exception:
continue
# Save debug HTML to file for inspection if needed
with open("selenium_debug.html", 'w', encoding='utf-8') as f:
f.write(driver.page_source)
driver.quit()
return 0
except Exception as e:
self.logger.error(f"Selenium scraping failed: {e}")
return None
def scrape_reel_data(self):
try:
headers = self._get_random_headers()
time.sleep(random.uniform(2, 5))
response = self.session.get(self.reel_url, headers=headers, timeout=30)
response.raise_for_status()
html_content = response.text
json_data = self._extract_json_data(html_content)
likes_count = 0
comments_count = 0
views_count = 0
if json_data:
try:
entry_data = json_data.get('entry_data', {})
post_page = entry_data.get('PostPage', [])
if post_page:
media = post_page[0].get('graphql', {}).get('shortcode_media', {})
likes_count = media.get('edge_media_preview_like', {}).get('count', 0)
comments_count = media.get('edge_media_to_comment', {}).get('count', 0)
views_count = media.get('video_view_count', 0)
except Exception:
pass
html_likes = self._extract_likes_from_html(html_content)
if html_likes > 0:
likes_count = html_likes
if likes_count == 0:
self.logger.info("No likes found via HTTP; trying Selenium fallback.")
selenium_likes = self.scrape_with_selenium()
if selenium_likes and selenium_likes > 0:
likes_count = selenium_likes
return {
'likes_count': likes_count,
'comments_count': comments_count,
'views_count': views_count,
'status': 'success',
}
except Exception as e:
self.logger.error(f"Scraping failed: {e}")
return {
'likes_count': 0,
'comments_count': 0,
'views_count': 0,
'status': f'error: {str(e)}',
}
def save_data_point(self, data):
timestamp = time.time()
datetime_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
row = [timestamp, datetime_str, data['likes_count'], data['comments_count'], data['views_count'], data['status']]
try:
with open(self.output_file, 'a', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(row)
self.logger.info(f"Saved data point: {datetime_str} Likes:{data['likes_count']}")
except Exception as e:
self.logger.error(f"Failed saving data: {e}")
# Thread-safety globals
scraped_data = []
data_lock = threading.Lock()
tracking_flag = False
def scraper_thread_func(url, dur_hours, interval_min):
global tracking_flag
tracking_flag = True
with data_lock:
scraped_data.clear()
scraper = InstagramLikesScraper(url)
iterations = int(dur_hours * 60 // interval_min)
for _ in range(iterations):
if not tracking_flag:
break
data = scraper.scrape_reel_data()
scraper.save_data_point(data)
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
record = {'datetime': now, **data}
with data_lock:
scraped_data.append(record)
time.sleep(interval_min * 60)
tracking_flag = False
# Streamlit UI
st.title("Instagram Reel Likes Tracker with Selenium Fallback")
url = st.text_input("Instagram Reel URL", placeholder="https://www.instagram.com/reel/xxxxxx/")
duration_hours = st.number_input("Duration (hours)", min_value=0.1, value=0.5, step=0.1)
interval_minutes = st.number_input("Interval (minutes)", min_value=0.1, value=1.0, step=0.1)
start = st.button("Start Tracking")
stop = st.button("Stop Tracking")
if start:
if not url.strip():
st.error("Please enter a valid Instagram reel URL.")
elif tracking_flag:
st.warning("Tracking already in progress.")
else:
threading.Thread(target=scraper_thread_func, args=(url, duration_hours, interval_minutes), daemon=True).start()
st.success("Started tracking.")
if stop:
if tracking_flag:
tracking_flag = False
st.warning("Stopping tracking...")
else:
st.info("Tracking is not currently running.")
st.write(f"Tracking status: {'Active' if tracking_flag else 'Stopped'}")
with data_lock:
data_copy = scraped_data.copy()
if data_copy:
df = pd.DataFrame(data_copy)
st.dataframe(df[['datetime', 'likes_count', 'comments_count', 'views_count', 'status']])
csv_bytes = df.to_csv(index=False).encode()
st.download_button("Download CSV", data=csv_bytes, file_name="instagram_likes.csv", mime="text/csv")
else:
st.info("No data captured yet.")
Selenium fallback only runs when HTTP scraping fails or returns 0 likes.
Multi-threaded with safe shared data and a clean Streamlit GUI.
The Selenium browser runs headless (no UI).
If you want help setting up ChromeDriver or improving this solution further, just ask!
def scrape_with_selenium(self):
if not SELENIUM_AVAILABLE:
self.logger.error("Selenium not installed. Install with: pip install selenium")
return None
try:
options = Options()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--window-size=1920,1080')
user_agent = random.choice(self.user_agents)
options.add_argument(f'--user-agent={user_agent}')
driver = webdriver.Chrome(options=options)
driver.get(self.reel_url)
time.sleep(6) # Wait for page JS to load fully
# Try to find likes count using XPath checking aria-label or text
xpath_candidates = [
"//button[contains(@aria-label, 'like')]/span/span",
"//section//div[contains(text(), 'like')]/preceding-sibling::span",
"//span[contains(text(), 'likes')]",
"//meta[@property='og:description']" # fallback to meta, where sometimes likes are encoded
]
for xpath in xpath_candidates:
try:
elems = driver.find_elements(By.XPATH, xpath)
for el in elems:
text = el.text.strip()
if text:
# Extract digits (likes count) from text, e.g. "13,749 likes"
match = re.search(r'(\d[\d,]*)', text)
if match:
count = int(match.group(1).replace(',', ''))
self.logger.info(f"Selenium found likes with xpath '{xpath}': {count}")
driver.quit()
return count
# Special case meta tag maybe
if 'meta' in xpath and elems:
content = elems[0].get_attribute('content')
match = re.search(r'(\d[\d,]*) likes', content)
if match:
count = int(match.group(1).replace(',', ''))
self.logger.info(f"Selenium found likes from meta tag: {count}")
driver.quit()
return count
except Exception:
continue
# Save debug source if failed:
with open("selenium_debug.html", 'w', encoding='utf-8') as f:
f.write(driver.page_source)
driver.quit()
self.logger.warning("Selenium could not find likes count, returning 0.")
return 0
except Exception as e:
self.logger.error(f"Selenium scraping failed: {e}")
return None
4. Manually inspect selenium_debug.html
When the likes are zero, open the selenium_debug.html saved file in your browser.
Inspect the page and search for "likes" string manually.
Find the proper CSS or XPath selector matching the likes count.
Adapt the code accordingly.
5. Bonus - Use Instagram's JSON inside <script> tags
Often the page includes a <script type="application/ld+json"> or some shared data JSON containing likes count, which you can also try to parse in Selenium by accessing driver.page_source and extracting the JSON blob similarly as you do with requests.
Summary
Try updating your Selenium fallback to use the improved selector logic above.
If you want, I can provide a full updated Streamlit app including this improved Selenium fallback.
If you want me to do that, just say, happy to help!