Skip to content

armgit / Scout

Public Imported from GitHub
0

Free lead generation tool. Scrape Instagram, Twitch, TikTok, and LinkedIn profiles. Extract emails from bios, verify via SMTP, export to CSV.

v1.3.0: CLI redesign, settings menu, update checker, instagram fixes

marcuse39f15480740
diff --git a/app/__init__.py b/app/__init__.py
index e231b0e..82be889 100644
--- a/app/__init__.py
+++ b/app/__init__.py
@@ -2,4 +2,4 @@
Scout - Social media lead generation tool.
"""
-__version__ = "1.2.0"
+__version__ = "1.3.0"
diff --git a/app/scrapers/github.py b/app/scrapers/github.py
index f74ea8e..3e643fc 100644
--- a/app/scrapers/github.py
+++ b/app/scrapers/github.py
@@ -1,9 +1,13 @@
"""
GitHub Profile Scraper
-Fetches public GitHub user profiles using the GitHub API.
-Extracts username, name, bio, email, company, location, website, and social links.
-No authentication required for basic profile data (60 requests/hour rate limit).
+Fetches public GitHub user profiles via the GitHub REST API.
+Extracts bio, follower counts, repos, company, location, and website.
+
+Features:
+- Uses unauthenticated API (60 requests/hour limit)
+- Skips empty profiles (no repos, no bio, no activity)
+- Extracts email from public profile fields
"""
import requests
diff --git a/app/scrapers/instagram.py b/app/scrapers/instagram.py
index 7a3afe5..5312289 100644
--- a/app/scrapers/instagram.py
+++ b/app/scrapers/instagram.py
@@ -29,7 +29,21 @@ MOBILE_USER_AGENTS = [
]
-def scrape_profile_no_login(username: str, max_retries: int = 7) -> Optional[Dict]:
+def _is_page_not_found(html: str) -> bool:
+ """Check if the HTML indicates the profile does not exist."""
+ not_found_signals = [
+ "Page Not Found",
+ "Sorry, this page isn",
+ "The link you followed may be broken",
+ "Profile isn\\'t available",
+ "profile may have been removed",
+ '"HttpErrorPage"',
+ ]
+ snippet = html[:10000]
+ return any(signal in snippet for signal in not_found_signals)
+
+
+def scrape_profile_no_login(username: str, max_retries: int = 3) -> Optional[Dict]:
"""Scrape Instagram profile using mobile web HTML parsing (no API)."""
import random
import time
@@ -49,14 +63,13 @@ def scrape_profile_no_login(username: str, max_retries: int = 7) -> Optional[Dic
r = requests.get(url, headers=headers, proxies=proxies, timeout=20)
if r.status_code == 404:
- logger.error(f"Profile @{username} not found")
return None
if r.status_code == 429:
raise RuntimeError("Rate limited by Instagram (429). Wait a few minutes before scraping again.")
if r.status_code != 200:
- logger.warning(f"HTTP {r.status_code} for @{username}, attempt {attempt + 1}/{max_retries}")
+ logger.debug(f"HTTP {r.status_code} for @{username}, attempt {attempt + 1}/{max_retries}")
if attempt < max_retries - 1:
time.sleep(1)
continue
@@ -64,28 +77,26 @@ def scrape_profile_no_login(username: str, max_retries: int = 7) -> Optional[Dic
html = r.text
- # Check if redirected to login
+ if _is_page_not_found(html):
+ return None
+
if '/accounts/login' in r.url or ('login' in html[:5000].lower() and 'password' in html[:5000].lower()):
- logger.error(f"Instagram requires login for @{username}")
return None
- # Extract data from embedded JSON in HTML
data = _extract_profile_from_html(html, username)
if data:
return data
- # Extraction failed - retry with new proxy/IP
if attempt < max_retries - 1:
logger.debug(f"Extraction failed for @{username}, retrying ({attempt + 1}/{max_retries})")
time.sleep(1.0)
continue
- logger.error(f"Could not extract profile data for @{username} after {max_retries} attempts")
return None
except requests.exceptions.Timeout:
- logger.warning(f"Timeout for @{username}, attempt {attempt + 1}/{max_retries}")
+ logger.debug(f"Timeout for @{username}, attempt {attempt + 1}/{max_retries}")
if attempt < max_retries - 1:
time.sleep(1)
continue
@@ -96,7 +107,7 @@ def scrape_profile_no_login(username: str, max_retries: int = 7) -> Optional[Dic
err = str(e)
if '429' in err:
raise RuntimeError("Rate limited by Instagram (429). Wait a few minutes before scraping again.")
- logger.warning(f"Error scraping @{username}: {e}, attempt {attempt + 1}/{max_retries}")
+ logger.debug(f"Error scraping @{username}: {e}, attempt {attempt + 1}/{max_retries}")
if attempt < max_retries - 1:
time.sleep(1)
continue
@@ -110,7 +121,6 @@ def _extract_profile_from_html(html: str, username: str) -> Optional[Dict]:
results = {}
- # Multiple patterns for username (Instagram changes HTML structure)
username_patterns = [
r'"username":"([^"]+)"',
r'"owner":\{"username":"([^"]+)"',
@@ -122,7 +132,6 @@ def _extract_profile_from_html(html: str, username: str) -> Optional[Dict]:
results['username'] = match.group(1)
break
- # Multiple patterns for full name
name_patterns = [
r'"full_name":"([^"]*)"',
r'"name":"([^"]*)"',
@@ -134,7 +143,6 @@ def _extract_profile_from_html(html: str, username: str) -> Optional[Dict]:
results['full_name'] = match.group(1).strip()
break
- # Multiple patterns for biography
bio_patterns = [
r'"biography":"([^"]*)"',
r'"bio":"([^"]*)"',
@@ -150,7 +158,6 @@ def _extract_profile_from_html(html: str, username: str) -> Optional[Dict]:
results['biography'] = match.group(1).replace('\\u', '')
break
- # Multiple patterns for follower count
follower_patterns = [
r'"follower_count":(\d+)',
r'"edge_followed_by":\{"count":(\d+)\}',
@@ -163,7 +170,6 @@ def _extract_profile_from_html(html: str, username: str) -> Optional[Dict]:
results['follower_count'] = int(match.group(1))
break
- # Multiple patterns for following count
following_patterns = [
r'"following_count":(\d+)',
r'"edge_follow":\{"count":(\d+)\}',
@@ -174,7 +180,6 @@ def _extract_profile_from_html(html: str, username: str) -> Optional[Dict]:
results['following_count'] = int(match.group(1))
break
- # Multiple patterns for media/post count
media_patterns = [
r'"media_count":(\d+)',
r'"edge_owner_to_timeline_media":\{"count":(\d+)\}',
@@ -185,7 +190,6 @@ def _extract_profile_from_html(html: str, username: str) -> Optional[Dict]:
results['media_count'] = int(match.group(1))
break
- # Meta description fallback: "11M Followers, 7,639 Following, 11K Posts"
meta_patterns = [
r'content="([\d.,]+[KMB]?)\s*Followers?,\s*([\d.,]+[KMB]?)\s*Following,\s*([\d.,]+[KMB]?)\s*Posts?',
r'([\d.,]+[KMB]?)\s*Followers?\s*[,·]\s*([\d.,]+[KMB]?)\s*Following\s*[,·]\s*([\d.,]+[KMB]?)\s*Posts?',
@@ -201,7 +205,6 @@ def _extract_profile_from_html(html: str, username: str) -> Optional[Dict]:
results['media_count'] = _parse_abbreviated_number(meta_match.group(3))
break
- # Get verified status
verified_patterns = [
r'"is_verified":(true|false)',
r'"verified":(true|false)',
@@ -212,17 +215,14 @@ def _extract_profile_from_html(html: str, username: str) -> Optional[Dict]:
results['is_verified'] = match.group(1) == 'true'
break
- # Get private status
match = re.search(r'"is_private":(true|false)', html)
if match:
results['is_private'] = match.group(1) == 'true'
- # Get business status
match = re.search(r'"is_business_account":(true|false)', html)
if match:
results['is_business'] = match.group(1) == 'true'
- # Get external URL
url_patterns = [
r'"external_url":"([^"]+)"',
r'"website":"([^"]+)"',
@@ -238,7 +238,6 @@ def _extract_profile_from_html(html: str, username: str) -> Optional[Dict]:
results['external_url'] = match.group(1).replace('\\/', '/')
break
- # Must have follower count to be considered valid
if 'follower_count' not in results or results.get('follower_count', 0) == 0:
return None
diff --git a/app/scrapers/linktree.py b/app/scrapers/linktree.py
index 96ade01..f103d9a 100644
--- a/app/scrapers/linktree.py
+++ b/app/scrapers/linktree.py
@@ -1,14 +1,18 @@
"""
Link-in-Bio Scraper
-Fetches profile data from link-in-bio services:
-- Linktree
-- Stan.store
-- Linkr.bio
-- Bio.link
-
-Extracts all links, social profiles, and contact info.
-No authentication required.
+Scrapes public link-in-bio pages across multiple platforms.
+
+Supported platforms:
+- Linktree (linktr.ee)
+- Stan Store (stan.store)
+- Linkr (linkr.bio)
+- Bio.link (bio.link)
+
+Features:
+- Extracts all social links from profile pages
+- Discovers email and phone from linked content
+- Can scrape all supported platforms at once via scrape_all()
"""
import requests
diff --git a/app/scrapers/pinterest.py b/app/scrapers/pinterest.py
index 2ffb735..c5fa360 100644
--- a/app/scrapers/pinterest.py
+++ b/app/scrapers/pinterest.py
@@ -1,9 +1,13 @@
"""
Pinterest Profile Scraper
-Fetches public Pinterest profile information by extracting JSON from HTML.
-Extracts username, display name, bio, follower count, and website.
-No authentication required.
+Scrapes public Pinterest user profiles by parsing HTML page data.
+Extracts follower counts, pin counts, bio, and website links.
+
+Features:
+- Parses embedded JSON from page source
+- No authentication required
+- Extracts email and phone from bio text
"""
import requests
diff --git a/app/scrapers/twitch.py b/app/scrapers/twitch.py
index 03f5654..8e75df4 100644
--- a/app/scrapers/twitch.py
+++ b/app/scrapers/twitch.py
@@ -1,9 +1,13 @@
"""
Twitch Profile Scraper
-Fetches public Twitch channel information using the Helix API.
-Extracts username, display name, bio, and profile image.
-No authentication required for basic channel info.
+Fetches public Twitch user profiles via the Twitch GQL API.
+Extracts follower counts, bio, stream status, and social links.
+
+Features:
+- Uses public GraphQL endpoint (no auth required)
+- Extracts social links from channel panels
+- Detects live/offline status
"""
import requests
diff --git a/app/scrapers/utils.py b/app/scrapers/utils.py
index 0302a81..9f062da 100644
--- a/app/scrapers/utils.py
+++ b/app/scrapers/utils.py
@@ -1,7 +1,12 @@
"""
-Shared scraper utilities.
+Shared Scraper Utilities
-Common extraction functions used across all platform scrapers.
+Common functions used across all platform scrapers.
+
+Provides:
+- extract_email() — regex-based email extraction from text
+- extract_phone() — phone number extraction from text
+- parse_abbreviated_number() — converts "11.5K", "2.3M" to integers
"""
import re
diff --git a/app/scrapers/youtube.py b/app/scrapers/youtube.py
index 9e0351d..965bc12 100644
--- a/app/scrapers/youtube.py
+++ b/app/scrapers/youtube.py
@@ -1,9 +1,13 @@
"""
YouTube Channel Scraper
-Fetches public YouTube channel information by parsing the channel page.
-Extracts channel name, description, subscriber count, and contact email from the About section.
-No authentication required.
+Scrapes public YouTube channel pages by parsing HTML and embedded JSON.
+Extracts subscriber counts, video counts, channel description, and links.
+
+Features:
+- Parses ytInitialData JSON from page source
+- Handles both @handle and /channel/ URL formats
+- No API key required
"""
import requests
diff --git a/scout.py b/scout.py
index 46a885e..23094a5 100644
--- a/scout.py
+++ b/scout.py
@@ -54,11 +54,12 @@ from rich.console import Console
from rich.panel import Panel
from rich.prompt import Prompt, Confirm
from rich.table import Table
-from rich.progress import Progress, SpinnerColumn, TextColumn
+from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, MofNCompleteColumn, TimeRemainingColumn
from rich import box
from rich.layout import Layout
from rich.text import Text
from rich.theme import Theme
+from rich.rule import Rule
from app.scrapers.instagram import scrape_profile_no_login
from app.scrapers.stealth import random_delay, proxy_status
@@ -66,6 +67,69 @@ from app.scrapers.stealth import random_delay, proxy_status
ACCENT = "#a70947"
ACCENT_DIM = "#6b0530"
ACCENT_LIGHT = "#d64d7a"
+ACCENT_MUTED = "#4a0727"
+
+_GRAD_START = (255, 107, 157)
+_GRAD_END = (167, 9, 71)
+
+_LOGO_LINES = [
+ "███████ ██████ ██████ ██ ██ ████████",
+ "██ ██ ██ ██ ██ ██ ██ ",
+ "███████ ██ ██ ██ ██ ██ ██ ",
+ " ██ ██ ██ ██ ██ ██ ██ ",
+ "███████ ██████ ██████ ████ ██ ",
+]
+
+_session_stats = {"scraped": 0}
+_update_cache = {"checked": False, "latest": None}
+
+
+def _check_for_updates():
+ """Check GitHub releases API for a newer version. Non-blocking, fails silently."""
+ if _update_cache["checked"]:
+ return _update_cache["latest"]
+
+ _update_cache["checked"] = True
+
+ try:
+ import requests as _req
+ resp = _req.get(
+ "https://api.github.com/repos/kiryano/Scout/releases/latest",
+ headers={"Accept": "application/vnd.github.v3+json"},
+ timeout=3,
+ )
+ if resp.status_code != 200:
+ return None
+
+ data = resp.json()
+ tag = data.get("tag_name", "")
+ latest = tag.lstrip("v").strip()
+ if not latest:
+ return None
+
+ def _ver(s):
+ try:
+ return tuple(int(x) for x in s.split("."))
+ except (ValueError, AttributeError):
+ return (0,)
+
+ if _ver(latest) > _ver(__version__):
+ _update_cache["latest"] = latest
+ return latest
+
+ except Exception:
+ pass
+
+ return None
+
+
+def _start_update_check():
+ """Fire off the update check in a background thread so it doesn't block startup."""
+ import threading
+ t = threading.Thread(target=_check_for_updates, daemon=True)
+ t.start()
+ return t
+
custom_theme = Theme({
"prompt.choices": ACCENT,
@@ -146,16 +210,15 @@ def enrich_profiles(profiles):
avg_score = sum(scores) // len(scores) if scores else 0
summary_parts.append(f"[white]Avg lead score: {avg_score}/100[/white]")
- console.print(Panel(
- "\n".join(summary_parts),
- title="[bold]Enrichment Results[/bold]",
- border_style=ACCENT_DIM
- ))
+ console.print(Rule("[bold white]Enrichment[/bold white]", style=ACCENT_DIM, align="left"))
+ console.print()
+ for part in summary_parts:
+ console.print(f" {part}")
+ console.print()
email_leads = [e for e in enriched if e.get('email')]
if email_leads:
- console.print()
- t = Table(show_header=True, box=box.SIMPLE)
+ t = Table(show_header=True, box=box.MINIMAL_HEAVY_HEAD, border_style="dim", padding=(0, 1))
t.add_column("Lead", style="white")
t.add_column("Email", style="white")
t.add_column("Confidence", style="green")
@@ -180,934 +243,470 @@ def enrich_profiles(profiles):
return enriched
-def show_header():
- logo = """
-███████╗ ██████╗ ██████╗ ██╗ ██╗████████╗
-██╔════╝██╔════╝██╔═══██╗██║ ██║╚══██╔══╝
-███████╗██║ ██║ ██║██║ ██║ ██║
-╚════██║██║ ██║ ██║██║ ██║ ██║
-███████║╚██████╗╚██████╔╝╚██████╔╝ ██║
-╚══════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝
- """
-
- console.print(logo, style=f"bold {ACCENT}", justify="center")
- console.print("[bold white]Free Lead Generation Tool[/bold white]", justify="center")
+def _platform_header(name: str, subtitle: str = "No login required"):
+ """Print a consistent platform header."""
console.print()
-
- info_table = Table(show_header=False, box=None, padding=(0, 2))
- info_table.add_column(justify="right", style="dim")
- info_table.add_column(style=f"{ACCENT}")
-
- info_table.add_row("Discord", "discord.gg/eneDNUbzcc")
- info_table.add_row("GitHub", "github.com/kiryano/Scout")
-
- ps = proxy_status()
- if ps == 'custom':
- info_table.add_row("Proxy", "[green]● custom[/green]")
- elif ps == 'file':
- info_table.add_row("Proxy", "[green]● rotating[/green]")
- elif ps == 'free':
- info_table.add_row("Proxy", "[yellow]● free[/yellow]")
- else:
- info_table.add_row("Proxy", "[dim]○ off[/dim]")
-
- console.print(info_table, justify="center")
- console.print()
-
-
-def show_menu():
- table = Table(
- show_header=False,
- box=None,
- padding=(0, 3),
- expand=False
- )
-
- table.add_column("", style=f"bold {ACCENT}", width=3)
- table.add_column("", style="white")
- table.add_column("", style="dim", width=20)
-
- table.add_row("1", "Instagram", "profiles")
- table.add_row("2", "TikTok", "profiles")
- table.add_row("3", "LinkedIn", "requires cookie")
- table.add_row("4", "GitHub", "profiles")
- table.add_row("5", "YouTube", "channels")
- table.add_row("6", "Twitch", "streamers")
- table.add_row("7", "Linktree", "link-in-bio")
- table.add_row("8", "Pinterest", "profiles")
- table.add_row("", "", "")
- table.add_row("9", "Bulk Scrape", "from file")
- table.add_row("10", "Exports", "view files")
- table.add_row("11", "Proxy", "settings")
- table.add_row("0", "Exit", "")
-
- console.print(Panel(
- table,
- title=f"[bold {ACCENT}]─── SELECT PLATFORM ───[/bold {ACCENT}]",
- border_style=ACCENT_DIM,
- box=box.HEAVY,
- padding=(1, 4)
+ console.print(Rule(
+ f"[bold white]{name}[/bold white] [dim]{subtitle}[/dim]",
+ style=ACCENT_DIM,
+ align="left"
))
console.print()
-def scrape_instagram_interactive():
- console.print()
- console.print(Panel(
- f"[bold {ACCENT}]INSTAGRAM[/bold {ACCENT}]\n[dim]No login required[/dim]",
- border_style=ACCENT_DIM,
- box=box.HEAVY
- ))
- console.print()
-
- console.print("[white]Enter Instagram usernames (one per line)[/white]")
- console.print("[dim]Press Enter on empty line when done[/dim]")
- console.print()
-
- usernames = []
- while True:
- username = Prompt.ask("Username", default="")
- if not username:
- break
- username = username.replace('@', '').strip()
- if username:
- usernames.append(username)
- console.print(f"[green]✓[/green] Added @{username}")
-
- if not usernames:
- console.print("[yellow]⚠ No usernames entered![/yellow]")
- return
-
- console.print()
- console.print(f"[bold white]Scraping {len(usernames)} profiles...[/bold white]")
- console.print()
-
- profiles = []
- successful = 0
-
- with Progress(
- SpinnerColumn(),
- TextColumn("[progress.description]{task.description}"),
- console=console
- ) as progress:
-
- for i, username in enumerate(usernames, 1):
- task = progress.add_task(
- f"[white]Scraping @{username}...",
- total=None
- )
-
- try:
- profile = scrape_profile_no_login(username)
-
- if profile:
- profiles.append(profile)
- successful += 1
-
- progress.update(task, description=f"[green]✓ @{username}")
-
- info_table = Table(show_header=False, box=None, padding=(0, 2))
- info_table.add_column(style="dim")
- info_table.add_column(style="white")
-
- info_table.add_row("Followers:", f"{profile['follower_count']:,}")
-
- if profile.get('full_name'):
- info_table.add_row("Name:", profile['full_name'][:50])
-
- if profile.get('bio'):
- bio = profile['bio'][:80] + '...' if len(profile['bio']) > 80 else profile['bio']
- info_table.add_row("Bio:", bio)
-
- if profile.get('email'):
- info_table.add_row("Email:", profile['email'])
-
- if profile.get('website'):
- info_table.add_row("Website:", profile['website'])
-
- console.print(info_table)
- console.print()
-
- else:
- progress.update(task, description=f"[red]✗ @{username} - Failed")
-
- except RuntimeError as e:
- progress.update(task, description=f"[red]✗ @{username} - Rate Limited")
- console.print(f"\n[bold red]⚠ {e}[/bold red]")
- break
- except Exception as e:
- progress.update(task, description=f"[red]✗ @{username} - Error")
- console.print(f"[dim red]Error: {str(e)[:100]}[/dim red]")
-
- if i < len(usernames):
- random_delay(1.5, 4.0)
-
- console.print()
-
- if profiles:
- result_panel = Panel(
- f"[bold green]Successfully scraped {successful}/{len(usernames)} profiles[/bold green]",
- style="green",
- box=box.DOUBLE
- )
- console.print(result_panel)
- console.print()
+def _profile_card(profile: dict):
+ """Display a scraped profile as a compact card."""
+ _session_stats["scraped"] += 1
+ lines = []
- profiles = enrich_profiles(profiles)
+ if profile.get('full_name'):
+ lines.append(f"[bold white]{profile['full_name'][:50]}[/bold white]")
- if Confirm.ask("[+] Export to CSV?", default=True):
- timestamp = time.strftime("%Y%m%d_%H%M%S")
- filename = f"instagram_export_{timestamp}.csv"
+ stats = []
+ if profile.get('follower_count'):
+ stats.append(f"[white]{profile['follower_count']:,}[/white] [dim]followers[/dim]")
+ if profile.get('following_count'):
+ stats.append(f"[white]{profile['following_count']:,}[/white] [dim]following[/dim]")
+ if stats:
+ lines.append(" · ".join(stats))
- with open(filename, 'w', newline='', encoding='utf-8') as f:
- if profiles:
- writer = csv.DictWriter(f, fieldnames=profiles[0].keys())
- writer.writeheader()
- writer.writerows(profiles)
+ email = profile.get('email', '')
+ if profile.get('bio'):
+ bio = profile['bio'].replace('\n', ' ')
+ if email:
+ bio = bio.replace(email, '').strip(' |·-,')
+ bio = bio[:80] + '...' if len(bio) > 80 else bio
+ if bio:
+ lines.append(f"[dim]{bio}[/dim]")
- console.print()
- console.print(Panel(
- f"[bold]Exported to:[/bold] [white]{filename}[/white]\n"
- f"[bold]Total profiles:[/bold] {len(profiles)}",
- title="[green]✓ Export Complete[/green]",
- border_style="green"
- ))
- else:
- console.print(Panel(
- "[yellow]No profiles were scraped successfully[/yellow]",
- style="yellow"
- ))
+ if email:
+ lines.append(f"[bold {ACCENT}]{email}[/bold {ACCENT}]")
+ if profile.get('website'):
+ lines.append(f"[dim]{profile['website']}[/dim]")
-def scrape_tiktok_interactive():
- from app.scrapers.tiktok import scrape_tiktok_profile
+ if profile.get('phone'):
+ lines.append(f"[dim]{profile['phone']}[/dim]")
- console.print()
+ username = profile.get('username', '?')
console.print(Panel(
- f"[bold {ACCENT}]TIKTOK[/bold {ACCENT}]\n[dim]No login required[/dim]",
+ "\n".join(lines) if lines else "[dim]No data[/dim]",
+ title=f"[bold white]@{username}[/bold white]",
+ title_align="left",
border_style=ACCENT_DIM,
- box=box.HEAVY
+ box=box.ROUNDED,
+ padding=(0, 2),
+ width=64
))
- console.print()
- console.print("[white]Enter TikTok usernames (one per line, without @)[/white]")
- console.print("[dim]Press Enter on empty line when done[/dim]")
- console.print()
- usernames = []
- while True:
- username = Prompt.ask("Username", default="")
- if not username:
- break
- username = username.replace('@', '').strip()
- if username:
- usernames.append(username)
- console.print(f"[green]✓[/green] Added @{username}")
-
- if not usernames:
- console.print("[yellow]⚠ No usernames entered![/yellow]")
- return
-
- console.print()
- console.print(f"[bold white]Scraping {len(usernames)} TikTok profiles...[/bold white]")
+def _success_summary(successful: int, total: int, item_type: str = "profiles"):
+ """Print a compact success summary line."""
console.print()
-
- profiles = []
-
- with Progress(
- SpinnerColumn(),
- TextColumn("[progress.description]{task.description}"),
- console=console
- ) as progress:
-
- for i, username in enumerate(usernames, 1):
- task = progress.add_task(
- f"[white]Scraping @{username}...",
- total=None
- )
-
- try:
- profile = scrape_tiktok_profile(username)
-
- if profile:
- profiles.append(profile)
-
- progress.update(task, description=f"[green]✓ @{username}")
-
- info_table = Table(show_header=False, box=None, padding=(0, 2))
- info_table.add_column(style="dim")
- info_table.add_column(style="white")
-
- if profile.get('follower_count'):
- info_table.add_row("Followers:", str(profile['follower_count']))
- if profile.get('full_name'):
- info_table.add_row("Name:", profile['full_name'][:50])
- if profile.get('bio'):
- bio = profile['bio'][:80] + '...' if len(profile['bio']) > 80 else profile['bio']
- info_table.add_row("Bio:", bio)
- if profile.get('email'):
- info_table.add_row("Email:", profile['email'])
-
- console.print(info_table)
- console.print()
- else:
- progress.update(task, description=f"[red]✗ @{username} - Failed")
-
- except Exception as e:
- progress.update(task, description=f"[red]✗ @{username} - Error")
- console.print(f"[dim red]Error: {str(e)[:100]}[/dim red]")
-
- if i < len(usernames):
- random_delay(2.0, 5.0)
-
- console.print()
-
- if profiles:
- result_panel = Panel(
- f"[bold green]Successfully scraped {len(profiles)}/{len(usernames)} profiles[/bold green]",
- style="green",
- box=box.DOUBLE
- )
- console.print(result_panel)
- console.print()
-
- profiles = enrich_profiles(profiles)
-
- if Confirm.ask("[+] Export to CSV?", default=True):
- timestamp = time.strftime("%Y%m%d_%H%M%S")
- filename = f"tiktok_export_{timestamp}.csv"
-
- with open(filename, 'w', newline='', encoding='utf-8') as f:
- if profiles:
- writer = csv.DictWriter(f, fieldnames=profiles[0].keys())
- writer.writeheader()
- writer.writerows(profiles)
-
- console.print()
- console.print(Panel(
- f"[bold]Exported to:[/bold] [white]{filename}[/white]\n"
- f"[bold]Total profiles:[/bold] {len(profiles)}",
- title="[green]✓ Export Complete[/green]",
- border_style="green"
- ))
+ if successful == total:
+ console.print(f" [green]OK[/green] [white]{successful}/{total} {item_type} scraped[/white]")
+ elif successful > 0:
+ console.print(f" [yellow]DONE[/yellow] [white]{successful}/{total} {item_type} scraped[/white]")
else:
- console.print(Panel(
- "[yellow]No profiles were scraped successfully[/yellow]",
- style="yellow"
- ))
-
-
-def scrape_linkedin_interactive():
- from app.scrapers.linkedin import scrape_linkedin_profile
-
+ console.print(f" [red]FAIL[/red] [white]0/{total} {item_type} scraped[/white]")
console.print()
- cookie = os.environ.get('LINKEDIN_COOKIE', '').strip()
- if not cookie:
- console.print(Panel(
- "[bold yellow]LinkedIn Cookie Required[/bold yellow]\n\n"
- "[white]To scrape LinkedIn profiles:[/white]\n"
- "1. Open Chrome and go to linkedin.com (logged in)\n"
- "2. Press F12 > Application > Cookies > linkedin.com\n"
- "3. Copy the value of [white]li_at[/white]\n"
- "4. Add to your .env file: [white]LINKEDIN_COOKIE=your_value_here[/white]\n"
- "5. Restart Scout",
- style="yellow",
- box=box.DOUBLE
- ))
- console.print()
- return
- console.print(Panel(
- f"[bold {ACCENT}]LINKEDIN[/bold {ACCENT}]\n[dim]Using session cookie[/dim]",
- border_style=ACCENT_DIM,
- box=box.HEAVY
- ))
- console.print()
-
- console.print("[white]Enter LinkedIn usernames or profile URLs (one per line)[/white]")
- console.print("[dim]Press Enter on empty line when done[/dim]")
+def _export_result(filename: str, count: int, item_type: str = "profiles"):
+ """Print a compact export confirmation line."""
+ console.print(f" [green]Saved[/green] [white]{filename}[/white] [dim]({count} {item_type})[/dim]")
console.print()
- usernames = []
- while True:
- entry = Prompt.ask("Username/URL", default="")
- if not entry:
- break
- entry = entry.strip().rstrip('/')
- if '/in/' in entry:
- entry = entry.split('/in/')[-1]
- entry = entry.lstrip('@').strip()
- if entry:
- usernames.append(entry)
- console.print(f"[green]✓[/green] Added {entry}")
-
- if not usernames:
- console.print("[yellow]No usernames entered![/yellow]")
- return
+def _no_results():
+ """Print no-results feedback."""
console.print()
- console.print(f"[bold white]Scraping {len(usernames)} LinkedIn profiles...[/bold white]")
+ console.print(" [yellow]No profiles were scraped successfully[/yellow]")
console.print()
- profiles = []
-
- with Progress(
- SpinnerColumn(),
- TextColumn("[progress.description]{task.description}"),
- console=console
- ) as progress:
-
- for i, username in enumerate(usernames, 1):
- task = progress.add_task(
- f"[white]Scraping {username}...",
- total=None
- )
-
- try:
- profile = scrape_linkedin_profile(username)
-
- if profile:
- profiles.append(profile)
-
- progress.update(task, description=f"[green]✓ {username}")
-
- info_table = Table(show_header=False, box=None, padding=(0, 2))
- info_table.add_column(style="dim")
- info_table.add_column(style="white")
-
- if profile.get('full_name'):
- info_table.add_row("Name:", profile['full_name'][:50])
- if profile.get('headline'):
- info_table.add_row("Title:", profile['headline'][:80])
- if profile.get('company'):
- info_table.add_row("Company:", profile['company'][:50])
- if profile.get('location'):
- info_table.add_row("Location:", profile['location'][:50])
- if profile.get('email'):
- info_table.add_row("Email:", profile['email'])
-
- console.print(info_table)
- console.print()
- else:
- progress.update(task, description=f"[red]✗ {username} - Failed")
-
- except Exception as e:
- progress.update(task, description=f"[red]✗ {username} - Error")
- console.print(f"[dim red]Error: {str(e)[:100]}[/dim red]")
-
- if i < len(usernames):
- random_delay(3.0, 6.0)
+def _pause():
+ """Pause before returning to menu so the user can review output."""
console.print()
+ console.print(Rule(style=ACCENT_MUTED))
+ Prompt.ask("[dim]Press Enter to continue[/dim]", default="")
+
+
+def _gradient_line(text: str, row: int, total_rows: int) -> Text:
+ """Apply a per-character color gradient across a line of text.
+ Row position shifts the gradient vertically (top rows lighter, bottom darker)."""
+ t = Text()
+ length = len(text.rstrip())
+ row_shift = row / max(total_rows - 1, 1)
+
+ for j, char in enumerate(text):
+ if j < length and char != ' ':
+ h_progress = j / max(length - 1, 1)
+ progress = h_progress * 0.6 + row_shift * 0.4
+ progress = max(0.0, min(1.0, progress))
+
+ r = int(_GRAD_START[0] + (_GRAD_END[0] - _GRAD_START[0]) * progress)
+ g = int(_GRAD_START[1] + (_GRAD_END[1] - _GRAD_START[1]) * progress)
+ b = int(_GRAD_START[2] + (_GRAD_END[2] - _GRAD_START[2]) * progress)
+ t.append(char, style=f"bold #{r:02x}{g:02x}{b:02x}")
+ else:
+ t.append(char)
+ return t
- if profiles:
- result_panel = Panel(
- f"[bold green]Successfully scraped {len(profiles)}/{len(usernames)} profiles[/bold green]",
- style="green",
- box=box.DOUBLE
- )
- console.print(result_panel)
- console.print()
-
- profiles = enrich_profiles(profiles)
-
- if Confirm.ask("[+] Export to CSV?", default=True):
- timestamp = time.strftime("%Y%m%d_%H%M%S")
- filename = f"linkedin_export_{timestamp}.csv"
- with open(filename, 'w', newline='', encoding='utf-8') as f:
- if profiles:
- writer = csv.DictWriter(f, fieldnames=profiles[0].keys())
- writer.writeheader()
- writer.writerows(profiles)
-
- console.print()
- console.print(Panel(
- f"[bold]Exported to:[/bold] [white]{filename}[/white]\n"
- f"[bold]Total profiles:[/bold] {len(profiles)}",
- title="[green]✓ Export Complete[/green]",
- border_style="green"
- ))
- else:
- console.print(Panel(
- "[yellow]No profiles were scraped successfully[/yellow]",
- style="yellow"
- ))
+def _gradient_bar() -> Text:
+ """Create a thin gradient bar spanning the terminal width."""
+ width = min(console.width, 80)
+ t = Text()
+ for j in range(width):
+ progress = j / max(width - 1, 1)
+ r = int(_GRAD_START[0] + (_GRAD_END[0] - _GRAD_START[0]) * progress)
+ g = int(_GRAD_START[1] + (_GRAD_END[1] - _GRAD_START[1]) * progress)
+ b = int(_GRAD_START[2] + (_GRAD_END[2] - _GRAD_START[2]) * progress)
+ t.append("▀", style=f"#{r:02x}{g:02x}{b:02x}")
+ return t
-def scrape_github_interactive():
- from app.scrapers.github import scrape_profile
-
+def show_header():
console.print()
- console.print(Panel(
- f"[bold {ACCENT}]GITHUB[/bold {ACCENT}]\n[dim]No login required[/dim]",
- border_style=ACCENT_DIM,
- box=box.HEAVY
- ))
+ console.print(_gradient_bar(), justify="center")
console.print()
- console.print("[white]Enter GitHub usernames (one per line)[/white]")
- console.print("[dim]Press Enter on empty line when done[/dim]")
- console.print()
+ total = len(_LOGO_LINES)
+ for i, line in enumerate(_LOGO_LINES):
+ t = _gradient_line(line, i, total)
+ console.print(t, justify="center")
- usernames = []
- while True:
- username = Prompt.ask("Username", default="")
- if not username:
- break
- username = username.strip()
- if username:
- usernames.append(username)
- console.print(f"[green]✓[/green] Added {username}")
-
- if not usernames:
- console.print("[yellow]No usernames entered![/yellow]")
- return
-
- console.print()
- console.print(f"[bold white]Scraping {len(usernames)} GitHub profiles...[/bold white]")
console.print()
-
- profiles = []
-
- with Progress(
- SpinnerColumn(),
- TextColumn("[progress.description]{task.description}"),
- console=console
- ) as progress:
-
- for i, username in enumerate(usernames, 1):
- task = progress.add_task(
- f"[white]Scraping {username}...",
- total=None
- )
-
- try:
- profile = scrape_profile(username)
-
- if profile:
- profiles.append(profile)
- progress.update(task, description=f"[green]✓ {username}")
-
- info_table = Table(show_header=False, box=None, padding=(0, 2))
- info_table.add_column(style="dim")
- info_table.add_column(style="white")
-
- if profile.get('full_name'):
- info_table.add_row("Name:", profile['full_name'][:50])
- if profile.get('follower_count'):
- info_table.add_row("Followers:", str(profile['follower_count']))
- if profile.get('bio'):
- bio = profile['bio'][:80] + '...' if len(profile['bio']) > 80 else profile['bio']
- info_table.add_row("Bio:", bio)
- if profile.get('email'):
- info_table.add_row("Email:", profile['email'])
- if profile.get('company'):
- info_table.add_row("Company:", profile['company'])
- if profile.get('website'):
- info_table.add_row("Website:", profile['website'])
-
- console.print(info_table)
- console.print()
- else:
- progress.update(task, description=f"[red]✗ {username} - Not found")
-
- except Exception as e:
- progress.update(task, description=f"[red]✗ {username} - Error")
- console.print(f"[dim red]Error: {str(e)[:100]}[/dim red]")
-
- if i < len(usernames):
- random_delay(0.5, 1.5)
+ console.print(f"[dim]v{__version__}[/dim] [white]Lead Generation Tool[/white]", justify="center")
console.print()
+ console.print(_gradient_bar(), justify="center")
- if profiles:
- result_panel = Panel(
- f"[bold green]Successfully scraped {len(profiles)}/{len(usernames)} profiles[/bold green]",
- style="green",
- box=box.DOUBLE
- )
- console.print(result_panel)
- console.print()
-
- profiles = enrich_profiles(profiles)
-
- if Confirm.ask("[+] Export to CSV?", default=True):
- timestamp = time.strftime("%Y%m%d_%H%M%S")
- filename = f"github_export_{timestamp}.csv"
-
- with open(filename, 'w', newline='', encoding='utf-8') as f:
- if profiles:
- writer = csv.DictWriter(f, fieldnames=profiles[0].keys())
- writer.writeheader()
- writer.writerows(profiles)
-
- console.print()
- console.print(Panel(
- f"[bold]Exported to:[/bold] [white]{filename}[/white]\n"
- f"[bold]Total profiles:[/bold] {len(profiles)}",
- title="[green]✓ Export Complete[/green]",
- border_style="green"
- ))
+ ps = proxy_status()
+ if ps == 'custom':
+ proxy_str = "[green]● custom[/green]"
+ elif ps == 'file':
+ proxy_str = "[green]● rotating[/green]"
+ elif ps == 'free':
+ proxy_str = "[yellow]● free[/yellow]"
else:
- console.print(Panel(
- "[yellow]No profiles were scraped successfully[/yellow]",
- style="yellow"
- ))
-
-
-def scrape_youtube_interactive():
- from app.scrapers.youtube import scrape_channel
-
- console.print()
- console.print(Panel(
- f"[bold {ACCENT}]YOUTUBE[/bold {ACCENT}]\n[dim]No login required[/dim]",
- border_style=ACCENT_DIM,
- box=box.HEAVY
- ))
- console.print()
-
- console.print("[white]Enter YouTube channel handles (e.g. @MrBeast) or channel IDs[/white]")
- console.print("[dim]Press Enter on empty line when done[/dim]")
- console.print()
-
- channels = []
- while True:
- channel = Prompt.ask("Channel", default="")
- if not channel:
- break
- channel = channel.strip()
- if channel:
- channels.append(channel)
- console.print(f"[green]✓[/green] Added {channel}")
-
- if not channels:
- console.print("[yellow]No channels entered![/yellow]")
- return
-
- console.print()
- console.print(f"[bold white]Scraping {len(channels)} YouTube channels...[/bold white]")
- console.print()
-
- profiles = []
-
- with Progress(
- SpinnerColumn(),
- TextColumn("[progress.description]{task.description}"),
- console=console
- ) as progress:
-
- for i, channel in enumerate(channels, 1):
- task = progress.add_task(
- f"[white]Scraping {channel}...",
- total=None
- )
-
- try:
- profile = scrape_channel(channel)
-
- if profile:
- profiles.append(profile)
- progress.update(task, description=f"[green]✓ {channel}")
-
- info_table = Table(show_header=False, box=None, padding=(0, 2))
- info_table.add_column(style="dim")
- info_table.add_column(style="white")
-
- if profile.get('full_name'):
- info_table.add_row("Name:", profile['full_name'][:50])
- if profile.get('follower_count'):
- info_table.add_row("Subscribers:", f"{profile['follower_count']:,}")
- if profile.get('bio'):
- bio = profile['bio'][:80] + '...' if len(profile['bio']) > 80 else profile['bio']
- info_table.add_row("Description:", bio)
- if profile.get('email'):
- info_table.add_row("Email:", profile['email'])
- if profile.get('website'):
- info_table.add_row("Website:", profile['website'])
-
- console.print(info_table)
- console.print()
- else:
- progress.update(task, description=f"[red]✗ {channel} - Not found")
-
- except Exception as e:
- progress.update(task, description=f"[red]✗ {channel} - Error")
- console.print(f"[dim red]Error: {str(e)[:100]}[/dim red]")
-
- if i < len(channels):
- random_delay(1.0, 2.5)
-
- console.print()
-
- if profiles:
- result_panel = Panel(
- f"[bold green]Successfully scraped {len(profiles)}/{len(channels)} channels[/bold green]",
- style="green",
- box=box.DOUBLE
+ proxy_str = "[dim]○ off[/dim]"
+
+ status = f"[dim]github.com/kiryano/Scout[/dim] · [dim]Proxy:[/dim] {proxy_str}"
+ if _session_stats["scraped"] > 0:
+ status += f" · [dim]Scraped:[/dim] [white]{_session_stats['scraped']}[/white]"
+ console.print(status, justify="center")
+
+ latest = _update_cache.get("latest")
+ if latest:
+ console.print(
+ f"[dim]Update available:[/dim] [bold {ACCENT}]v{latest}[/bold {ACCENT}] "
+ f"[dim]— pip install --upgrade scout or visit GitHub[/dim]",
+ justify="center"
)
- console.print(result_panel)
- console.print()
-
- profiles = enrich_profiles(profiles)
-
- if Confirm.ask("[+] Export to CSV?", default=True):
- timestamp = time.strftime("%Y%m%d_%H%M%S")
- filename = f"youtube_export_{timestamp}.csv"
-
- with open(filename, 'w', newline='', encoding='utf-8') as f:
- if profiles:
- writer = csv.DictWriter(f, fieldnames=profiles[0].keys())
- writer.writeheader()
- writer.writerows(profiles)
-
- console.print()
- console.print(Panel(
- f"[bold]Exported to:[/bold] [white]{filename}[/white]\n"
- f"[bold]Total channels:[/bold] {len(profiles)}",
- title="[green]✓ Export Complete[/green]",
- border_style="green"
- ))
- else:
- console.print(Panel(
- "[yellow]No channels were scraped successfully[/yellow]",
- style="yellow"
- ))
-
-
-def scrape_twitch_interactive():
- from app.scrapers.twitch import scrape_profile
- console.print()
- console.print(Panel(
- f"[bold {ACCENT}]TWITCH[/bold {ACCENT}]\n[dim]No login required[/dim]",
- border_style=ACCENT_DIM,
- box=box.HEAVY
- ))
console.print()
- console.print("[white]Enter Twitch usernames (one per line)[/white]")
- console.print("[dim]Press Enter on empty line when done[/dim]")
- console.print()
- usernames = []
- while True:
- username = Prompt.ask("Username", default="")
- if not username:
- break
- username = username.strip()
- if username:
- usernames.append(username)
- console.print(f"[green]✓[/green] Added {username}")
+def show_menu():
+ console.print(Rule("[bold white]Platforms[/bold white]", style=ACCENT_DIM, align="left"))
+ console.print()
- if not usernames:
- console.print("[yellow]No usernames entered![/yellow]")
- return
+ platforms_left = [
+ ("1", "Instagram", "profiles"),
+ ("2", "TikTok", "profiles"),
+ ("3", "LinkedIn", "cookie"),
+ ("4", "GitHub", "profiles"),
+ ("5", "YouTube", "channels"),
+ ]
+ platforms_right = [
+ ("6", "Twitch", "streamers"),
+ ("7", "Linktree", "link-in-bio"),
+ ("8", "Pinterest", "profiles"),
+ ]
+
+ table = Table(show_header=False, box=None, padding=(0, 0), pad_edge=False, expand=False)
+ table.add_column("", width=35)
+ table.add_column("", width=35)
+
+ max_rows = max(len(platforms_left), len(platforms_right))
+ for i in range(max_rows):
+ left = ""
+ right = ""
+ if i < len(platforms_left):
+ n, name, desc = platforms_left[i]
+ left = f" [{ACCENT}][{n}][/{ACCENT}] [bold white]{name}[/bold white] [dim]{desc}[/dim]"
+ if i < len(platforms_right):
+ n, name, desc = platforms_right[i]
+ right = f" [{ACCENT}][{n}][/{ACCENT}] [bold white]{name}[/bold white] [dim]{desc}[/dim]"
+ table.add_row(left, right)
+ console.print(table)
console.print()
- console.print(f"[bold white]Scraping {len(usernames)} Twitch profiles...[/bold white]")
+
+ console.print(Rule("[bold white]Tools[/bold white]", style=ACCENT_DIM, align="left"))
console.print()
- profiles = []
+ tools_left = [
+ ("9", "Bulk Scrape", "from file"),
+ ("10", "Exports", "view files"),
+ ]
+ tools_right = [
+ ("11", "Settings", "config"),
+ ("0", "Exit", ""),
+ ]
+
+ tools = Table(show_header=False, box=None, padding=(0, 0), pad_edge=False, expand=False)
+ tools.add_column("", width=35)
+ tools.add_column("", width=35)
+
+ for i in range(max(len(tools_left), len(tools_right))):
+ left = ""
+ right = ""
+ if i < len(tools_left):
+ n, name, desc = tools_left[i]
+ left = f" [{ACCENT}][{n}][/{ACCENT}] [bold white]{name}[/bold white] [dim]{desc}[/dim]"
+ if i < len(tools_right):
+ n, name, desc = tools_right[i]
+ right = f" [{ACCENT}][{n}][/{ACCENT}] [bold white]{name}[/bold white] [dim]{desc}[/dim]"
+ tools.add_row(left, right)
+
+ console.print(tools)
+ console.print()
- with Progress(
- SpinnerColumn(),
- TextColumn("[progress.description]{task.description}"),
- console=console
- ) as progress:
- for i, username in enumerate(usernames, 1):
- task = progress.add_task(
- f"[white]Scraping {username}...",
- total=None
- )
+def _get_delay_range(fallback=(1.0, 2.5)):
+ """Get configured delay range from env vars, with fallback."""
+ try:
+ d_min = float(os.environ.get('SCOUT_DELAY_MIN', str(fallback[0])))
+ d_max = float(os.environ.get('SCOUT_DELAY_MAX', str(fallback[1])))
+ return (d_min, d_max) if d_max >= d_min >= 0 else fallback
+ except ValueError:
+ return fallback
+
+
+def _standard_scrape_loop(scraper_func, items, label_prefix="@", delay_range=None):
+ """Shared scrape loop: spinner per item, then profile card. Clean output."""
+ if delay_range is None:
+ delay_range = _get_delay_range()
+ profiles = []
+ for i, item in enumerate(items, 1):
+ with Progress(SpinnerColumn(), TextColumn("[progress.description]{task.description}"), console=console, transient=True) as progress:
+ task = progress.add_task(f"[white]Scraping {label_prefix}{item} [dim]({i}/{len(items)})[/dim]", total=None)
try:
- profile = scrape_profile(username)
+ prev_level = logging.getLogger().level
+ if not _verbose:
+ logging.getLogger().setLevel(logging.CRITICAL)
+ profile = scraper_func(item)
+ if not _verbose:
+ logging.getLogger().setLevel(prev_level)
if profile:
profiles.append(profile)
- progress.update(task, description=f"[green]✓ {username}")
-
- info_table = Table(show_header=False, box=None, padding=(0, 2))
- info_table.add_column(style="dim")
- info_table.add_column(style="white")
-
- if profile.get('full_name'):
- info_table.add_row("Name:", profile['full_name'][:50])
- if profile.get('follower_count'):
- info_table.add_row("Followers:", f"{profile['follower_count']:,}")
- if profile.get('bio'):
- bio = profile['bio'][:80] + '...' if len(profile['bio']) > 80 else profile['bio']
- info_table.add_row("Bio:", bio)
- if profile.get('is_partner'):
- info_table.add_row("Status:", "[purple]Partner[/purple]")
- elif profile.get('is_affiliate'):
- info_table.add_row("Status:", "[blue]Affiliate[/blue]")
- if profile.get('email'):
- info_table.add_row("Email:", profile['email'])
-
- console.print(info_table)
- console.print()
+ progress.stop()
+ _profile_card(profile)
else:
- progress.update(task, description=f"[red]✗ {username} - Not found")
-
+ progress.stop()
+ console.print(f" [red]✗[/red] [dim]{label_prefix}{item} — not found[/dim]")
+ except RuntimeError as e:
+ if not _verbose:
+ logging.getLogger().setLevel(prev_level)
+ progress.stop()
+ console.print(f" [bold red]✗ {label_prefix}{item} — rate limited[/bold red]")
+ break
except Exception as e:
- progress.update(task, description=f"[red]✗ {username} - Error")
- console.print(f"[dim red]Error: {str(e)[:100]}[/dim red]")
+ if not _verbose:
+ logging.getLogger().setLevel(prev_level)
+ progress.stop()
+ console.print(f" [red]✗[/red] [dim]{label_prefix}{item} — {str(e)[:80]}[/dim]")
- if i < len(usernames):
- random_delay(0.5, 1.5)
+ if i < len(items):
+ random_delay(*delay_range)
- console.print()
+ return profiles
- if profiles:
- result_panel = Panel(
- f"[bold green]Successfully scraped {len(profiles)}/{len(usernames)} profiles[/bold green]",
- style="green",
- box=box.DOUBLE
- )
- console.print(result_panel)
- console.print()
+def _standard_export(profiles, total, platform_name, item_type="profiles"):
+ """Shared post-scrape: summary, enrichment, CSV export."""
+ if profiles:
+ _success_summary(len(profiles), total, item_type)
profiles = enrich_profiles(profiles)
-
if Confirm.ask("[+] Export to CSV?", default=True):
timestamp = time.strftime("%Y%m%d_%H%M%S")
- filename = f"twitch_export_{timestamp}.csv"
-
+ filename = f"{platform_name}_export_{timestamp}.csv"
with open(filename, 'w', newline='', encoding='utf-8') as f:
if profiles:
writer = csv.DictWriter(f, fieldnames=profiles[0].keys())
writer.writeheader()
writer.writerows(profiles)
-
- console.print()
- console.print(Panel(
- f"[bold]Exported to:[/bold] [white]{filename}[/white]\n"
- f"[bold]Total profiles:[/bold] {len(profiles)}",
- title="[green]✓ Export Complete[/green]",
- border_style="green"
- ))
+ _export_result(filename, len(profiles), item_type)
else:
- console.print(Panel(
- "[yellow]No profiles were scraped successfully[/yellow]",
- style="yellow"
- ))
+ _no_results()
-def scrape_linktree_interactive():
- from app.scrapers.linktree import scrape_linktree, scrape_all
-
+def _collect_usernames(platform_name, prompt_label="Username", strip_at=False):
+ """Shared username input loop. Returns list of usernames."""
+ console.print(f"[white]Enter {platform_name} usernames (one per line)[/white]")
+ console.print("[dim]Press Enter on empty line when done[/dim]")
console.print()
- console.print(Panel(
- f"[bold {ACCENT}]LINK-IN-BIO[/bold {ACCENT}]\n[dim]Linktree, Stan & more[/dim]",
- border_style=ACCENT_DIM,
- box=box.HEAVY
- ))
+
+ items = []
+ while True:
+ entry = Prompt.ask(prompt_label, default="")
+ if not entry:
+ break
+ if strip_at:
+ entry = entry.replace('@', '')
+ entry = entry.strip()
+ if entry:
+ items.append(entry)
+ prefix = "@" if strip_at else ""
+ console.print(f"[green]✓[/green] Added {prefix}{entry}")
+
+ if not items:
+ console.print("[yellow]No usernames entered[/yellow]")
+ return items
+
+
+def scrape_instagram_interactive():
+ _platform_header("Instagram")
+ usernames = _collect_usernames("Instagram", strip_at=True)
+ if not usernames:
+ return
console.print()
+ profiles = _standard_scrape_loop(scrape_profile_no_login, usernames, label_prefix="@", delay_range=(1.5, 4.0))
+ _standard_export(profiles, len(usernames), "instagram")
- console.print(f"[bold {ACCENT}]Select platform:[/bold {ACCENT}]")
- console.print("[1] Linktree (linktr.ee)")
- console.print("[2] Auto-detect (try all)")
+
+def scrape_tiktok_interactive():
+ from app.scrapers.tiktok import scrape_tiktok_profile
+ _platform_header("TikTok")
+ usernames = _collect_usernames("TikTok", strip_at=True)
+ if not usernames:
+ return
console.print()
+ profiles = _standard_scrape_loop(scrape_tiktok_profile, usernames, label_prefix="@", delay_range=(2.0, 5.0))
+ _standard_export(profiles, len(usernames), "tiktok")
- platform_choice = Prompt.ask("[>] Platform", choices=["1", "2"], default="1")
- scraper_map = {
- "1": (scrape_linktree, "linktree"),
- "2": (scrape_all, "linkbio"),
- }
- scraper_func, platform_name = scraper_map[platform_choice]
+def scrape_linkedin_interactive():
+ from app.scrapers.linkedin import scrape_linkedin_profile
- console.print()
- console.print("[white]Enter usernames (one per line)[/white]")
+ cookie = os.environ.get('LINKEDIN_COOKIE', '').strip()
+ if not cookie:
+ console.print()
+ console.print(Rule("[bold yellow]LinkedIn Cookie Required[/bold yellow]", style="yellow", align="left"))
+ console.print()
+ console.print(" [white]1.[/white] Open Chrome > linkedin.com (logged in)")
+ console.print(" [white]2.[/white] F12 > Application > Cookies > linkedin.com")
+ console.print(" [white]3.[/white] Copy the value of [bold]li_at[/bold]")
+ console.print(" [white]4.[/white] Add to .env: [bold]LINKEDIN_COOKIE=your_value[/bold]")
+ console.print(" [white]5.[/white] Restart Scout")
+ console.print()
+ return
+
+ _platform_header("LinkedIn", "Using session cookie")
+
+ console.print("[white]Enter LinkedIn usernames or profile URLs (one per line)[/white]")
console.print("[dim]Press Enter on empty line when done[/dim]")
console.print()
usernames = []
while True:
- username = Prompt.ask("Username", default="")
- if not username:
+ entry = Prompt.ask("Username/URL", default="")
+ if not entry:
break
- username = username.strip()
- if username:
- usernames.append(username)
- console.print(f"[green]✓[/green] Added {username}")
+ entry = entry.strip().rstrip('/')
+ if '/in/' in entry:
+ entry = entry.split('/in/')[-1]
+ entry = entry.lstrip('@').strip()
+ if entry:
+ usernames.append(entry)
+ console.print(f"[green]✓[/green] Added {entry}")
if not usernames:
- console.print("[yellow]No usernames entered![/yellow]")
+ console.print("[yellow]No usernames entered[/yellow]")
return
console.print()
- console.print(f"[bold white]Scraping {len(usernames)} profiles...[/bold white]")
+ profiles = _standard_scrape_loop(scrape_linkedin_profile, usernames, label_prefix="", delay_range=(3.0, 6.0))
+ _standard_export(profiles, len(usernames), "linkedin")
+
+
+def scrape_github_interactive():
+ from app.scrapers.github import scrape_profile
+ _platform_header("GitHub")
+ usernames = _collect_usernames("GitHub")
+ if not usernames:
+ return
console.print()
+ profiles = _standard_scrape_loop(scrape_profile, usernames, label_prefix="", delay_range=(0.5, 1.5))
+ _standard_export(profiles, len(usernames), "github")
- profiles = []
- with Progress(
- SpinnerColumn(),
- TextColumn("[progress.description]{task.description}"),
- console=console
- ) as progress:
+def scrape_youtube_interactive():
+ from app.scrapers.youtube import scrape_channel
+ _platform_header("YouTube")
- for i, username in enumerate(usernames, 1):
- task = progress.add_task(
- f"[white]Scraping {username}...",
- total=None
- )
+ console.print("[white]Enter YouTube channel handles (e.g. @MrBeast) or channel IDs[/white]")
+ console.print("[dim]Press Enter on empty line when done[/dim]")
+ console.print()
- try:
- profile = scraper_func(username)
+ channels = []
+ while True:
+ channel = Prompt.ask("Channel", default="")
+ if not channel:
+ break
+ channel = channel.strip()
+ if channel:
+ channels.append(channel)
+ console.print(f"[green]✓[/green] Added {channel}")
- if profile:
- profiles.append(profile)
- progress.update(task, description=f"[green]✓ {username}")
-
- info_table = Table(show_header=False, box=None, padding=(0, 2))
- info_table.add_column(style="dim")
- info_table.add_column(style="white")
-
- if profile.get('full_name'):
- info_table.add_row("Name:", profile['full_name'][:50])
- if profile.get('link_count'):
- info_table.add_row("Links:", str(profile['link_count']))
- if profile.get('bio'):
- bio = profile['bio'][:80] + '...' if len(profile['bio']) > 80 else profile['bio']
- info_table.add_row("Bio:", bio)
- if profile.get('email'):
- info_table.add_row("Email:", profile['email'])
- if profile.get('socials'):
- socials = profile['socials']
- social_str = ', '.join([f"{k}" for k in list(socials.keys())[:4]])
- info_table.add_row("Socials:", social_str)
-
- console.print(info_table)
- console.print()
- else:
- progress.update(task, description=f"[red]✗ {username} - Not found")
+ if not channels:
+ console.print("[yellow]No channels entered[/yellow]")
+ return
- except Exception as e:
- progress.update(task, description=f"[red]✗ {username} - Error")
- console.print(f"[dim red]Error: {str(e)[:100]}[/dim red]")
+ console.print()
+ profiles = _standard_scrape_loop(scrape_channel, channels, label_prefix="", delay_range=(1.0, 2.5))
+ _standard_export(profiles, len(channels), "youtube", "channels")
- if i < len(usernames):
- random_delay(0.5, 1.5)
+def scrape_twitch_interactive():
+ from app.scrapers.twitch import scrape_profile
+ _platform_header("Twitch")
+ usernames = _collect_usernames("Twitch")
+ if not usernames:
+ return
console.print()
+ profiles = _standard_scrape_loop(scrape_profile, usernames, label_prefix="", delay_range=(0.5, 1.5))
+ _standard_export(profiles, len(usernames), "twitch")
- if profiles:
- result_panel = Panel(
- f"[bold green]Successfully scraped {len(profiles)}/{len(usernames)} profiles[/bold green]",
- style="green",
- box=box.DOUBLE
- )
- console.print(result_panel)
- console.print()
- profiles = enrich_profiles(profiles)
+def scrape_linktree_interactive():
+ from app.scrapers.linktree import scrape_linktree, scrape_all
+ _platform_header("Link-in-Bio", "Linktree, Stan & more")
+
+ console.print("[1] Linktree (linktr.ee)")
+ console.print("[2] Auto-detect (try all)")
+ console.print()
+ platform_choice = Prompt.ask("[>] Platform", choices=["1", "2"], default="1")
+
+ scraper_map = {"1": (scrape_linktree, "linktree"), "2": (scrape_all, "linkbio")}
+ scraper_func, platform_name = scraper_map[platform_choice]
+
+ console.print()
+ usernames = _collect_usernames("link-in-bio")
+ if not usernames:
+ return
+ console.print()
+ profiles = _standard_scrape_loop(scraper_func, usernames, label_prefix="", delay_range=(0.5, 1.5))
+
+ if profiles:
+ _success_summary(len(profiles), len(usernames))
+ profiles = enrich_profiles(profiles)
if Confirm.ask("[+] Export to CSV?", default=True):
timestamp = time.strftime("%Y%m%d_%H%M%S")
filename = f"{platform_name}_export_{timestamp}.csv"
@@ -1128,151 +727,24 @@ def scrape_linktree_interactive():
writer = csv.DictWriter(f, fieldnames=sorted(all_keys))
writer.writeheader()
writer.writerows(export_profiles)
-
- console.print()
- console.print(Panel(
- f"[bold]Exported to:[/bold] [white]{filename}[/white]\n"
- f"[bold]Total profiles:[/bold] {len(profiles)}",
- title="[green]✓ Export Complete[/green]",
- border_style="green"
- ))
+ _export_result(filename, len(profiles))
else:
- console.print(Panel(
- "[yellow]No profiles were scraped successfully[/yellow]",
- style="yellow"
- ))
+ _no_results()
def scrape_pinterest_interactive():
from app.scrapers.pinterest import scrape_profile
-
- console.print()
- console.print(Panel(
- f"[bold {ACCENT}]PINTEREST[/bold {ACCENT}]\n[dim]No login required[/dim]",
- border_style=ACCENT_DIM,
- box=box.HEAVY
- ))
- console.print()
-
- console.print("[white]Enter Pinterest usernames (one per line)[/white]")
- console.print("[dim]Press Enter on empty line when done[/dim]")
- console.print()
-
- usernames = []
- while True:
- username = Prompt.ask("Username", default="")
- if not username:
- break
- username = username.strip()
- if username:
- usernames.append(username)
- console.print(f"[green]✓[/green] Added {username}")
-
+ _platform_header("Pinterest")
+ usernames = _collect_usernames("Pinterest")
if not usernames:
- console.print("[yellow]No usernames entered![/yellow]")
return
-
- console.print()
- console.print(f"[bold white]Scraping {len(usernames)} Pinterest profiles...[/bold white]")
- console.print()
-
- profiles = []
-
- with Progress(
- SpinnerColumn(),
- TextColumn("[progress.description]{task.description}"),
- console=console
- ) as progress:
-
- for i, username in enumerate(usernames, 1):
- task = progress.add_task(
- f"[white]Scraping {username}...",
- total=None
- )
-
- try:
- profile = scrape_profile(username)
-
- if profile:
- profiles.append(profile)
- progress.update(task, description=f"[green]✓ {username}")
-
- info_table = Table(show_header=False, box=None, padding=(0, 2))
- info_table.add_column(style="dim")
- info_table.add_column(style="white")
-
- if profile.get('full_name'):
- info_table.add_row("Name:", profile['full_name'][:50])
- if profile.get('follower_count'):
- info_table.add_row("Followers:", f"{profile['follower_count']:,}")
- if profile.get('pin_count'):
- info_table.add_row("Pins:", f"{profile['pin_count']:,}")
- if profile.get('board_count'):
- info_table.add_row("Boards:", f"{profile['board_count']:,}")
- if profile.get('bio'):
- bio = profile['bio'][:80] + '...' if len(profile['bio']) > 80 else profile['bio']
- info_table.add_row("Bio:", bio)
- if profile.get('website'):
- info_table.add_row("Website:", profile['website'])
- if profile.get('email'):
- info_table.add_row("Email:", profile['email'])
-
- console.print(info_table)
- console.print()
- else:
- progress.update(task, description=f"[red]✗ {username} - Not found")
-
- except Exception as e:
- progress.update(task, description=f"[red]✗ {username} - Error")
- console.print(f"[dim red]Error: {str(e)[:100]}[/dim red]")
-
- if i < len(usernames):
- random_delay(1.0, 2.5)
-
console.print()
-
- if profiles:
- result_panel = Panel(
- f"[bold green]Successfully scraped {len(profiles)}/{len(usernames)} profiles[/bold green]",
- style="green",
- box=box.DOUBLE
- )
- console.print(result_panel)
- console.print()
-
- profiles = enrich_profiles(profiles)
-
- if Confirm.ask("[+] Export to CSV?", default=True):
- timestamp = time.strftime("%Y%m%d_%H%M%S")
- filename = f"pinterest_export_{timestamp}.csv"
-
- with open(filename, 'w', newline='', encoding='utf-8') as f:
- if profiles:
- writer = csv.DictWriter(f, fieldnames=profiles[0].keys())
- writer.writeheader()
- writer.writerows(profiles)
-
- console.print()
- console.print(Panel(
- f"[bold]Exported to:[/bold] [white]{filename}[/white]\n"
- f"[bold]Total profiles:[/bold] {len(profiles)}",
- title="[green]✓ Export Complete[/green]",
- border_style="green"
- ))
- else:
- console.print(Panel(
- "[yellow]No profiles were scraped successfully[/yellow]",
- style="yellow"
- ))
+ profiles = _standard_scrape_loop(scrape_profile, usernames, label_prefix="", delay_range=(1.0, 2.5))
+ _standard_export(profiles, len(usernames), "pinterest")
def scrape_from_file():
- console.print()
- console.print(Panel(
- f"[bold {ACCENT}]BULK SCRAPE[/bold {ACCENT}]\n[dim]From username list file (TXT or CSV)[/dim]",
- border_style=ACCENT_DIM,
- box=box.HEAVY
- ))
+ _platform_header("Bulk Scrape", "From username list file")
console.print()
filename = Prompt.ask("[>] Enter filename", default="usernames.txt")
@@ -1358,43 +830,36 @@ def scrape_from_file():
profiles = []
successful = 0
- with Progress(
- SpinnerColumn(),
- TextColumn("[progress.description]{task.description}"),
- console=console
- ) as progress:
-
- for i, username in enumerate(usernames, 1):
- task = progress.add_task(
- f"[{i}/{len(usernames)}] @{username}...",
- total=None
- )
+ for i, username in enumerate(usernames, 1):
+ with Progress(SpinnerColumn(), TextColumn("[progress.description]{task.description}"), console=console, transient=True) as progress:
+ task = progress.add_task(f"[white]@{username} [dim]({i}/{len(usernames)})[/dim]", total=None)
try:
+ prev_level = logging.getLogger().level
+ if not _verbose:
+ logging.getLogger().setLevel(logging.CRITICAL)
profile = scraper_func(username)
+ if not _verbose:
+ logging.getLogger().setLevel(prev_level)
if profile:
profiles.append(profile)
successful += 1
follower_count = profile.get('follower_count', 0) or profile.get('subscribers', 0) or 0
- progress.update(
- task,
- description=f"[green]✓[/green] [{i}/{len(usernames)}] @{username} ({follower_count:,} followers)"
- )
+ progress.stop()
+ console.print(f" [green]✓[/green] @{username} [dim]{follower_count:,} followers[/dim]")
else:
- progress.update(
- task,
- description=f"[red]✗[/red] [{i}/{len(usernames)}] @{username}"
- )
+ progress.stop()
+ console.print(f" [red]✗[/red] [dim]@{username}[/dim]")
except Exception as e:
- progress.update(
- task,
- description=f"[red]✗[/red] [{i}/{len(usernames)}] @{username}"
- )
+ if not _verbose:
+ logging.getLogger().setLevel(prev_level)
+ progress.stop()
+ console.print(f" [red]✗[/red] [dim]@{username}[/dim]")
- if i < len(usernames):
- random_delay(1.5, 4.0)
+ if i < len(usernames):
+ random_delay(*_get_delay_range((1.5, 4.0)))
console.print()
@@ -1408,20 +873,10 @@ def scrape_from_file():
writer.writeheader()
writer.writerows(profiles)
- console.print(Panel(
- f"[bold green]SUCCESS![/bold green]\n\n"
- f"[bold]Platform:[/bold] {platform_name}\n"
- f"[bold]Scraped:[/bold] {successful}/{len(usernames)} profiles\n"
- f"[bold]Exported to:[/bold] [white]{export_filename}[/white]",
- title="[green]✓ Complete[/green]",
- border_style="green",
- box=box.DOUBLE
- ))
+ _success_summary(successful, len(usernames))
+ _export_result(export_filename, successful)
else:
- console.print(Panel(
- "[yellow]No profiles were scraped successfully[/yellow]",
- style="yellow"
- ))
+ _no_results()
except FileNotFoundError:
console.print(f"\n[red]✗ Error: File '{filename}' not found![/red]")
@@ -1429,61 +884,67 @@ def scrape_from_file():
console.print(f"\n[red]✗ Error: {e}[/red]")
-def proxy_settings():
- import httpx as _httpx
-
- console.print()
- console.print(Panel(
- f"[bold {ACCENT}]PROXY SETTINGS[/bold {ACCENT}]\n[dim]Configure proxy for scraping[/dim]",
- border_style=ACCENT_DIM,
- box=box.HEAVY
- ))
- console.print()
+def settings_menu():
+ _platform_header("Settings", "Configure Scout")
ps = proxy_status()
current_proxy = os.environ.get('SCOUT_PROXY', '')
free_enabled = os.environ.get('SCOUT_FREE_PROXY', '').lower() in ('1', 'true', 'yes')
-
- status_table = Table(show_header=False, box=None, padding=(0, 2))
- status_table.add_column(style="dim")
- status_table.add_column(style="white")
proxy_file = os.environ.get('SCOUT_PROXY_FILE', '')
+ delay_min = os.environ.get('SCOUT_DELAY_MIN', '1.0')
+ delay_max = os.environ.get('SCOUT_DELAY_MAX', '2.5')
+ li_cookie = os.environ.get('LINKEDIN_COOKIE', '').strip()
- status_table.add_row("Status:", f"[green]{ps}[/green]" if ps != 'none' else "[red]off[/red]")
+ proxy_str = f"[green]{ps}[/green]" if ps != 'none' else "[red]off[/red]"
if current_proxy:
- status_table.add_row("Proxy URL:", current_proxy[:60])
- if proxy_file:
- status_table.add_row("Proxy File:", proxy_file[:60])
- status_table.add_row("Free Proxy:", "[green]on[/green]" if free_enabled else "[dim]off[/dim]")
- console.print(status_table)
+ proxy_str += f" [dim]{current_proxy[:40]}[/dim]"
+ elif proxy_file:
+ proxy_str += f" [dim]{proxy_file[:40]}[/dim]"
+
+ console.print(f" [dim]Proxy:[/dim] {proxy_str}")
+ console.print(f" [dim]Free proxy:[/dim] [green]on[/green]" if free_enabled else f" [dim]Free proxy:[/dim] [dim]off[/dim]")
+ console.print(f" [dim]Delay:[/dim] [white]{delay_min}s - {delay_max}s[/white]")
+ console.print(f" [dim]LinkedIn:[/dim] [green]cookie set[/green]" if li_cookie else f" [dim]LinkedIn:[/dim] [dim]not configured[/dim]")
+ console.print(f" [dim]Scraped:[/dim] [white]{_session_stats['scraped']}[/white] [dim]this session[/dim]")
+ console.print()
+
+ console.print(Rule("[bold white]Proxy[/bold white]", style=ACCENT_DIM, align="left"))
+ console.print()
+ console.print(f" [{ACCENT}][1][/{ACCENT}] Set proxy URL")
+ console.print(f" [{ACCENT}][2][/{ACCENT}] Set proxy file")
+ console.print(f" [{ACCENT}][3][/{ACCENT}] Toggle free proxy")
+ console.print(f" [{ACCENT}][4][/{ACCENT}] Test connection")
+ console.print(f" [{ACCENT}][5][/{ACCENT}] Remove proxy")
console.print()
- options = Table(show_header=False, box=box.ROUNDED, style="yellow", padding=(0, 2))
- options.add_column("Option", style="bold yellow", width=8)
- options.add_column("Description", style="white")
- options.add_row("1", "Set proxy URL")
- options.add_row("2", "Set proxy file (rotating list)")
- options.add_row("3", "Toggle free proxy on/off")
- options.add_row("4", "Test proxy connection")
- options.add_row("5", "Remove proxy")
- options.add_row("6", "Back to menu")
- console.print(options)
+ console.print(Rule("[bold white]Scraping[/bold white]", style=ACCENT_DIM, align="left"))
+ console.print()
+ console.print(f" [{ACCENT}][6][/{ACCENT}] Set scrape delay")
+ console.print(f" [{ACCENT}][7][/{ACCENT}] Set LinkedIn cookie")
+ console.print()
+
+ console.print(Rule("[bold white]Data[/bold white]", style=ACCENT_DIM, align="left"))
+ console.print()
+ console.print(f" [{ACCENT}][8][/{ACCENT}] Clear all exports")
+ console.print(f" [{ACCENT}][0][/{ACCENT}] Back to menu")
console.print()
- choice = Prompt.ask("[bold yellow]Choose[/bold yellow]", choices=["1", "2", "3", "4", "5", "6"], default="6")
+ choice = Prompt.ask(f"[{ACCENT}]>[/{ACCENT}]", choices=["0", "1", "2", "3", "4", "5", "6", "7", "8"], default="0")
+
+ import httpx as _httpx
if choice == '1':
- url = Prompt.ask("[>] Enter proxy URL (e.g. http://user:pass@host:port)")
+ url = Prompt.ask("[>] Proxy URL (e.g. http://user:pass@host:port)")
if url.strip():
_update_env('SCOUT_PROXY', url.strip())
- console.print(f"[green]✓ Proxy set to {url.strip()[:60]}[/green]")
+ console.print(f"[green]✓ Proxy set[/green]")
elif choice == '2':
- filepath = Prompt.ask("[>] Enter path to proxy list file (one proxy per line)")
+ filepath = Prompt.ask("[>] Path to proxy list file")
if filepath.strip():
if os.path.exists(filepath.strip()):
_update_env('SCOUT_PROXY_FILE', filepath.strip())
- console.print(f"[green]✓ Proxy file set to {filepath.strip()[:60]}[/green]")
+ console.print(f"[green]✓ Proxy file set[/green]")
else:
console.print(f"[red]✗ File not found: {filepath.strip()}[/red]")
@@ -1496,19 +957,19 @@ def proxy_settings():
console.print("[green]✓ Free proxy enabled[/green]")
elif choice == '4':
- console.print("[white]Testing proxy connection...[/white]")
+ console.print("[white]Testing connection...[/white]")
from app.scrapers.stealth import get_proxy
px = get_proxy()
if not px:
- console.print("[yellow]No proxy configured. Testing direct connection...[/yellow]")
+ console.print("[dim]No proxy configured, testing direct...[/dim]")
try:
resp = _httpx.get('https://httpbin.org/ip', timeout=10)
ip = resp.json().get('origin', '?')
- console.print(f"[green]✓ Direct connection works. Your IP: {ip}[/green]")
+ console.print(f"[green]✓ Direct connection works. IP: {ip}[/green]")
except Exception as e:
- console.print(f"[red]✗ Connection failed: {str(e)[:100]}[/red]")
+ console.print(f"[red]✗ Connection failed: {str(e)[:80]}[/red]")
else:
- console.print(f"[dim]Trying proxy: {px[:60]}[/dim]")
+ console.print(f"[dim]Trying: {px[:60]}[/dim]")
proxy_url = px if px.startswith('http') else f'http://{px}'
try:
resp = _httpx.get('https://httpbin.org/ip', proxy=proxy_url, timeout=10, verify=False)
@@ -1517,9 +978,8 @@ def proxy_settings():
except Exception as e:
console.print(f"[red]✗ Proxy failed: {str(e)[:80]}[/red]")
if free_enabled:
- console.print("[yellow]Free proxies are unreliable. Trying another...[/yellow]")
+ console.print("[yellow]Free proxies are unreliable. Trying others...[/yellow]")
from app.scrapers.stealth import _fetch_free_proxies
- import random as _rand
proxies = _fetch_free_proxies()
for p in proxies[:3]:
p_url = p if p.startswith('http') else f'http://{p}'
@@ -1532,7 +992,7 @@ def proxy_settings():
except Exception:
console.print(f"[red]✗ Dead[/red]")
else:
- console.print("[red]All free proxies failed. Use a paid proxy for reliability.[/red]")
+ console.print("[red]All free proxies failed. Use a paid proxy.[/red]")
elif choice == '5':
_update_env('SCOUT_PROXY', '')
@@ -1542,31 +1002,55 @@ def proxy_settings():
os.environ.pop('SCOUT_PROXY_FILE', None)
console.print("[yellow]✓ Proxy removed[/yellow]")
+ elif choice == '6':
+ console.print(f"[dim]Current: {delay_min}s - {delay_max}s between requests[/dim]")
+ new_min = Prompt.ask("[>] Min delay (seconds)", default=delay_min)
+ new_max = Prompt.ask("[>] Max delay (seconds)", default=delay_max)
+ try:
+ fmin, fmax = float(new_min), float(new_max)
+ if fmin < 0 or fmax < fmin:
+ console.print("[red]✗ Invalid range[/red]")
+ else:
+ _update_env('SCOUT_DELAY_MIN', str(fmin))
+ _update_env('SCOUT_DELAY_MAX', str(fmax))
+ console.print(f"[green]✓ Delay set to {fmin}s - {fmax}s[/green]")
+ except ValueError:
+ console.print("[red]✗ Must be numbers[/red]")
+
+ elif choice == '7':
+ console.print("[white]Paste your LinkedIn li_at cookie value:[/white]")
+ console.print("[dim]Chrome > F12 > Application > Cookies > linkedin.com > li_at[/dim]")
+ cookie = Prompt.ask("[>] li_at", default="")
+ if cookie.strip():
+ _update_env('LINKEDIN_COOKIE', cookie.strip())
+ console.print("[green]✓ LinkedIn cookie saved[/green]")
+
+ elif choice == '8':
+ csv_files = list(Path('.').glob('*_export_*.csv'))
+ if not csv_files:
+ console.print("[yellow]No exports to clear[/yellow]")
+ else:
+ console.print(f"[yellow]This will delete {len(csv_files)} export file(s)[/yellow]")
+ if Confirm.ask("[>] Continue?", default=False):
+ for f in csv_files:
+ f.unlink()
+ console.print(f"[green]✓ Deleted {len(csv_files)} exports[/green]")
+
+
def view_exports():
- console.print()
- console.print(Panel(
- f"[bold {ACCENT}]EXPORTS[/bold {ACCENT}]\n[dim]Your scraped data[/dim]",
- border_style=ACCENT_DIM,
- box=box.HEAVY
- ))
- console.print()
+ _platform_header("Exports", "Your scraped data")
csv_files = list(Path('.').glob('*_export_*.csv'))
if not csv_files:
- console.print("[yellow]No exports found yet![/yellow]")
- console.print("[dim]Run a scrape to create your first export[/dim]")
+ console.print(" [yellow]No exports found yet[/yellow]")
+ console.print(" [dim]Run a scrape to create your first export[/dim]")
return
csv_files.sort(key=lambda x: x.stat().st_mtime, reverse=True)
- table = Table(
- title=f"[bold]Found {len(csv_files)} exports[/bold]",
- box=box.ROUNDED,
- style=ACCENT_DIM
- )
-
+ table = Table(box=box.MINIMAL_HEAVY_HEAD, border_style="dim", padding=(0, 1))
table.add_column("#", style="dim", width=4)
table.add_column("Filename", style="white")
table.add_column("Size", style="white", justify="right")
@@ -1575,19 +1059,17 @@ def view_exports():
for i, file in enumerate(csv_files[:10], 1):
size = file.stat().st_size / 1024
mtime = time.strftime("%Y-%m-%d %H:%M", time.localtime(file.stat().st_mtime))
-
- table.add_row(
- str(i),
- file.name,
- f"{size:.1f} KB",
- mtime
- )
+ table.add_row(str(i), file.name, f"{size:.1f} KB", mtime)
console.print(table)
+ console.print(f" [dim]{len(csv_files)} exports total[/dim]")
+ console.print()
def main():
+ _update_thread = _start_update_check()
console.clear()
+ _update_thread.join(timeout=2.0)
show_header()
while True:
@@ -1595,58 +1077,51 @@ def main():
try:
choice = Prompt.ask(
- f"[bold {ACCENT}]>[/bold {ACCENT}] [{ACCENT}]0-11[/{ACCENT}]",
+ f"[{ACCENT}]>[/{ACCENT}]",
choices=["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"],
default="1",
show_choices=False
)
+ if choice == '0':
+ console.clear()
+ console.print()
+ console.print(Rule(style=ACCENT_DIM))
+ console.print(
+ f" [bold {ACCENT}]Thanks for using Scout[/bold {ACCENT}] "
+ "[dim]★ github.com/kiryano/Scout[/dim]"
+ )
+ console.print()
+ break
+
+ console.clear()
+
if choice == '1':
scrape_instagram_interactive()
-
elif choice == '2':
scrape_tiktok_interactive()
-
elif choice == '3':
scrape_linkedin_interactive()
-
elif choice == '4':
scrape_github_interactive()
-
elif choice == '5':
scrape_youtube_interactive()
-
elif choice == '6':
scrape_twitch_interactive()
-
elif choice == '7':
scrape_linktree_interactive()
-
elif choice == '8':
scrape_pinterest_interactive()
-
elif choice == '9':
scrape_from_file()
-
elif choice == '10':
view_exports()
-
elif choice == '11':
- proxy_settings()
-
- elif choice == '0':
- console.print()
- console.print(Panel(
- f"[bold {ACCENT}]Thanks for using Scout![/bold {ACCENT}]\n\n"
- "[white]★ Star us on GitHub[/white]\n"
- "[dim]github.com/kiryano/Scout[/dim]\n\n"
- "[dim]Made for appointment setters[/dim]",
- border_style=ACCENT_DIM,
- box=box.HEAVY
- ))
- break
+ settings_menu()
- console.print(f"\n[{ACCENT_DIM}]{'━' * 50}[/{ACCENT_DIM}]\n")
+ _pause()
+ console.clear()
+ show_header()
except KeyboardInterrupt:
console.print("\n\n[yellow]Exiting...[/yellow]")