Spaces:
Sleeping
Sleeping
Piers Lyon
Claude Opus 4.6
Refactor into multipage Streamlit app with new intelligence features
b8f40ca Download linkedin_intel.py from mipwr-admin/curium-intel: direct link, hf CLI and curl.
- Browser
- Download file 45.6 kB
-
https://huggingface.co/spaces/mipwr-admin/curium-intel/resolve/main/linkedin_intel.py
- Command line
-
hf download hf://spaces/mipwr-admin/curium-intel/linkedin_intel.py
-
curl -L -o linkedin_intel.py https://huggingface.co/spaces/mipwr-admin/curium-intel/resolve/main/linkedin_intel.py
45.6 kB
"""
LinkedIn Intelligence Module (linkedin_intel.py)
Authenticated LinkedIn scraping via Playwright persistent browser profile.
Uses a real browser session to gather deep intelligence:
- Profile data (title, company, activity, mutual connections)
- Profile activity (posts, engagement, interaction with team)
- Company pages (size, industry, recent hires, decision-makers)
- Feed scanning for transformation trigger keywords
- LinkedIn URL resolution from name + company
Anti-ban strategy:
- Persistent browser profile (login once, reuse cookies)
- Human-like delays (3-8s between page loads)
- Session limits (40 profiles + 10 companies per run)
- Daily caps tracked in SQLite (80 profiles/day, 20 companies/day)
- Random scroll patterns and jitter
- Graceful degradation on rate limiting / CAPTCHA
"""
import os
import re
import time
import random
import sqlite3
import logging
from datetime import datetime, date
from pathlib import Path
from urllib.parse import quote_plus
logger = logging.getLogger(__name__)
PROFILE_DIR = os.path.expanduser("~/.curium-linkedin-profile")
DATABASE = "leads.db"
DAILY_LIMITS = {
"profile_views": 200,
"company_views": 40,
"searches": 30,
}
# Delay settings (overridable from config)
DEFAULT_MIN_DELAY = 3
DEFAULT_MAX_DELAY = 8
DEFAULT_PAGE_LOAD_WAIT = 2
# =============================================================================
# DAILY USAGE TRACKING
# =============================================================================
def _init_usage_table():
"""Create daily usage tracking table if not exists."""
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS linkedin_daily_usage (
id INTEGER PRIMARY KEY AUTOINCREMENT,
usage_date TEXT NOT NULL,
profile_views INTEGER DEFAULT 0,
company_views INTEGER DEFAULT 0,
searches INTEGER DEFAULT 0,
UNIQUE(usage_date)
)
""")
conn.commit()
conn.close()
def _init_url_cache_table():
"""Create LinkedIn URL cache table if not exists."""
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS linkedin_urls (
id INTEGER PRIMARY KEY AUTOINCREMENT,
contact_name TEXT NOT NULL,
company TEXT,
linkedin_url TEXT,
date_resolved TEXT NOT NULL,
UNIQUE(contact_name, company)
)
""")
conn.commit()
conn.close()
def check_daily_limits() -> dict:
"""Check remaining daily quota. Resets at midnight."""
_init_usage_table()
today = date.today().isoformat()
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
cursor.execute(
"SELECT profile_views, company_views, searches FROM linkedin_daily_usage WHERE usage_date = ?",
(today,)
)
row = cursor.fetchone()
conn.close()
if row:
used_profiles, used_companies, used_searches = row
else:
used_profiles, used_companies, used_searches = 0, 0, 0
return {
"profile_views": DAILY_LIMITS["profile_views"] - used_profiles,
"company_views": DAILY_LIMITS["company_views"] - used_companies,
"searches": DAILY_LIMITS["searches"] - used_searches,
"used_profiles": used_profiles,
"used_companies": used_companies,
"used_searches": used_searches,
}
def _increment_usage(usage_type: str, count: int = 1):
"""Increment daily usage counter."""
_init_usage_table()
today = date.today().isoformat()
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
# Ensure row exists for today
cursor.execute(
"INSERT OR IGNORE INTO linkedin_daily_usage (usage_date) VALUES (?)",
(today,)
)
if usage_type == "profile_views":
cursor.execute(
"UPDATE linkedin_daily_usage SET profile_views = profile_views + ? WHERE usage_date = ?",
(count, today)
)
elif usage_type == "company_views":
cursor.execute(
"UPDATE linkedin_daily_usage SET company_views = company_views + ? WHERE usage_date = ?",
(count, today)
)
elif usage_type == "searches":
cursor.execute(
"UPDATE linkedin_daily_usage SET searches = searches + ? WHERE usage_date = ?",
(count, today)
)
conn.commit()
conn.close()
# =============================================================================
# BROWSER SESSION MANAGEMENT
# =============================================================================
def create_linkedin_context(playwright, headless: bool = True):
"""
Create a persistent Playwright browser context using saved LinkedIn session.
If no cookies exist (first run), opens a visible browser for manual login.
Subsequent runs reuse the saved session headlessly.
Returns: (browser, context, page)
"""
os.makedirs(PROFILE_DIR, exist_ok=True)
# Check if we have a saved session
has_session = os.path.exists(os.path.join(PROFILE_DIR, "Default", "Cookies")) or \
os.path.exists(os.path.join(PROFILE_DIR, "Cookies"))
if not has_session:
headless = False # Force visible for first login
browser = playwright.chromium.launch_persistent_context(
user_data_dir=PROFILE_DIR,
headless=headless,
viewport={"width": 1280, "height": 900},
user_agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
locale="en-GB",
timezone_id="Europe/London",
args=[
"--disable-blink-features=AutomationControlled",
"--no-sandbox",
],
)
page = browser.pages[0] if browser.pages else browser.new_page()
return browser, page
def setup_linkedin_login(playwright):
"""
Interactive login setup. Opens a visible browser for user to log in manually.
Saves session to persistent profile directory.
The persistent context auto-saves cookies/session data to PROFILE_DIR,
so even if the user closes the browser window, the session is preserved
as long as they completed the login.
Returns True if login was successful.
"""
os.makedirs(PROFILE_DIR, exist_ok=True)
browser, page = create_linkedin_context(playwright, headless=False)
try:
page.goto("https://www.linkedin.com/login", wait_until="networkidle")
except Exception:
# Browser may have been closed immediately
pass
time.sleep(2)
# Wait for user to complete login (check for feed or nav elements)
# We'll wait up to 5 minutes for manual login
logged_in = False
for _ in range(300): # 300 seconds = 5 minutes
try:
if is_logged_in(page):
logged_in = True
break
except Exception:
# Browser was closed by user — session may still be saved
# since persistent context writes cookies to disk on navigation
break
time.sleep(1)
if logged_in:
# Navigate to feed to ensure session is fully established
try:
page.goto("https://www.linkedin.com/feed/", wait_until="networkidle")
time.sleep(3)
except Exception:
# Browser closed after login detected — session already saved
pass
try:
browser.close()
except Exception:
pass # Already closed by user
# If user closed the browser, check if session was saved by verifying
# the profile directory has meaningful content
if not logged_in:
status = get_linkedin_session_status()
if status == "connected":
logged_in = True
return logged_in
def is_logged_in(page) -> bool:
"""Check if currently logged into LinkedIn by looking for nav elements."""
try:
# Check for the global nav bar that only appears when logged in
selectors = [
'div.global-nav',
'nav[aria-label="Primary"]',
'a[href*="/feed/"]',
'li.global-nav__primary-item',
'div.feed-identity-module',
]
for selector in selectors:
try:
if page.query_selector(selector):
return True
except Exception:
continue
# Check URL - if we're on feed or any logged-in page
url = page.url
if '/feed' in url or '/mynetwork' in url or '/messaging' in url:
return True
return False
except Exception:
return False
def get_linkedin_session_status() -> str:
"""
Check LinkedIn session status.
Returns: 'connected', 'expired', or 'not_configured'
"""
if not os.path.exists(PROFILE_DIR):
return "not_configured"
# Check if profile directory has meaningful content
has_data = False
for root, dirs, files in os.walk(PROFILE_DIR):
if files:
has_data = True
break
if not has_data:
return "not_configured"
# Check age of session data
profile_path = Path(PROFILE_DIR)
try:
# Look for any recently modified files (within 7 days)
newest_mtime = 0
for f in profile_path.rglob("*"):
if f.is_file():
mtime = f.stat().st_mtime
if mtime > newest_mtime:
newest_mtime = mtime
if newest_mtime == 0:
return "not_configured"
days_old = (time.time() - newest_mtime) / 86400
if days_old > 7:
return "expired"
return "connected"
except Exception:
return "not_configured"
# =============================================================================
# HUMAN-LIKE BEHAVIOUR
# =============================================================================
def _human_delay(min_s: float = None, max_s: float = None):
"""Sleep for a random human-like duration."""
min_s = min_s or DEFAULT_MIN_DELAY
max_s = max_s or DEFAULT_MAX_DELAY
delay = random.uniform(min_s, max_s)
time.sleep(delay)
def _random_scroll(page, scrolls: int = None):
"""Perform random scroll behaviour to look human."""
if scrolls is None:
scrolls = random.randint(2, 5)
for _ in range(scrolls):
scroll_amount = random.randint(200, 600)
page.evaluate(f"window.scrollBy(0, {scroll_amount})")
time.sleep(random.uniform(0.5, 1.5))
# Sometimes scroll back up a bit
if random.random() < 0.3:
page.evaluate(f"window.scrollBy(0, -{random.randint(100, 300)})")
time.sleep(random.uniform(0.3, 0.8))
def _check_for_rate_limit(page) -> bool:
"""Check if LinkedIn is showing rate limiting or CAPTCHA."""
try:
url = page.url
content = page.content()
# Check for known rate-limit indicators
rate_limit_signals = [
"challenge" in url.lower(),
"captcha" in url.lower(),
"checkpoint" in url.lower(),
"security-verification" in url.lower(),
"too many requests" in content.lower(),
"unusual activity" in content.lower(),
]
return any(rate_limit_signals)
except Exception:
return False
# =============================================================================
# PROFILE SCRAPING
# =============================================================================
def scrape_profile(page, linkedin_url: str) -> dict:
"""
Visit a LinkedIn profile and extract key information.
Returns dict with: title, company, location, headline, about, experience,
education, skills, mutual_connections, connection_degree, recent_posts,
last_active_date
"""
result = {
"url": linkedin_url,
"title": "",
"company": "",
"location": "",
"headline": "",
"about": "",
"experience": [],
"education": [],
"skills": [],
"mutual_count": 0,
"degree": 0,
"recent_posts": [],
"last_active_date": "",
}
try:
page.goto(linkedin_url, wait_until="domcontentloaded")
time.sleep(DEFAULT_PAGE_LOAD_WAIT)
_random_scroll(page, scrolls=3)
if _check_for_rate_limit(page):
logger.warning("Rate limit detected during profile scrape")
raise Exception("LinkedIn rate limit detected")
# Extract headline/title
for selector in [
"div.text-body-medium.break-words",
"h2.mt1.t-18",
".pv-text-details__left-panel h2",
]:
try:
el = page.query_selector(selector)
if el:
result["headline"] = el.inner_text().strip()
break
except Exception:
continue
# Extract name (for verification)
for selector in [
"h1.text-heading-xlarge",
"h1.pv-text-details__left-panel",
"li.inline.t-24",
]:
try:
el = page.query_selector(selector)
if el:
result["name"] = el.inner_text().strip()
break
except Exception:
continue
# Extract current position and company from the top card
try:
# Current title is often in the headline or the experience section
exp_items = page.query_selector_all("li.artdeco-list__item")
if not exp_items:
exp_items = page.query_selector_all("section.artdeco-card li")
for item in exp_items[:1]: # First experience item = current role
text = item.inner_text()
lines = [l.strip() for l in text.split("\n") if l.strip()]
if len(lines) >= 2:
result["title"] = lines[0]
result["company"] = lines[1] if len(lines) > 1 else ""
except Exception:
pass
# Extract location
for selector in [
"span.text-body-small.inline.t-black--light.break-words",
".pv-text-details__left-panel span.t-black--light",
]:
try:
el = page.query_selector(selector)
if el:
result["location"] = el.inner_text().strip()
break
except Exception:
continue
# Extract About section
try:
about_section = page.query_selector("section.pv-about-section")
if not about_section:
about_section = page.query_selector("#about ~ div")
if about_section:
result["about"] = about_section.inner_text().strip()[:500]
except Exception:
pass
# Extract connection degree and mutual connections from page text
# LinkedIn's DOM classes change frequently, so text-based extraction is more robust
try:
body_text = page.inner_text("body")
# Connection degree: look for "1st", "2nd", "3rd" in the page text
degree_match = re.search(r'\b(\d)(?:st|nd|rd)\b', body_text)
if degree_match:
result["degree"] = int(degree_match.group(1))
# Mutual connections
mutual_match = re.search(r'(\d+)\s*mutual\s*connection', body_text, re.IGNORECASE)
if mutual_match:
result["mutual_count"] = int(mutual_match.group(1))
except Exception:
pass
# Extract experience (last 3 roles)
try:
_random_scroll(page, scrolls=2)
exp_section = page.query_selector("#experience")
if exp_section:
exp_items = exp_section.query_selector_all("li.artdeco-list__item")
for item in exp_items[:3]:
try:
text = item.inner_text()
lines = [l.strip() for l in text.split("\n") if l.strip()]
if lines:
exp_entry = {
"title": lines[0] if lines else "",
"company": lines[1] if len(lines) > 1 else "",
"duration": lines[2] if len(lines) > 2 else "",
}
result["experience"].append(exp_entry)
except Exception:
continue
except Exception:
pass
_increment_usage("profile_views")
except Exception as e:
logger.error(f"Profile scrape failed for {linkedin_url}: {e}")
raise
return result
def scrape_profile_activity(page, linkedin_url: str) -> list:
"""
Navigate to a profile's recent activity and extract posts.
Returns list of dicts with: text, post_type, likes, comments,
reposts, date, team_interacted
"""
activities = []
activity_url = f"{linkedin_url.rstrip('/')}/recent-activity/all/"
try:
page.goto(activity_url, wait_until="domcontentloaded")
time.sleep(DEFAULT_PAGE_LOAD_WAIT)
_random_scroll(page, scrolls=3)
if _check_for_rate_limit(page):
logger.warning("Rate limit detected during activity scrape")
return activities
# Find post containers
post_selectors = [
"div.feed-shared-update-v2",
"div.occludable-update",
"article.feed-shared-update",
]
posts = []
for selector in post_selectors:
posts = page.query_selector_all(selector)
if posts:
break
for post in posts[:5]: # Last 5 posts
try:
post_data = {
"text": "",
"post_type": "original",
"likes": 0,
"comments": 0,
"reposts": 0,
"date": "",
"team_interacted": False,
}
# Extract post text
try:
text_el = post.query_selector("span.break-words")
if not text_el:
text_el = post.query_selector("div.feed-shared-text")
if text_el:
post_data["text"] = text_el.inner_text().strip()[:200]
except Exception:
pass
# Determine post type (original, repost, comment)
try:
header = post.query_selector("span.feed-shared-header")
if header:
header_text = header.inner_text().lower()
if "repost" in header_text or "shared" in header_text:
post_data["post_type"] = "repost"
elif "commented" in header_text:
post_data["post_type"] = "comment"
elif "article" in header_text:
post_data["post_type"] = "article"
except Exception:
pass
# Extract engagement counts
try:
social_counts = post.query_selector("ul.social-details-social-counts")
if social_counts:
counts_text = social_counts.inner_text()
likes_match = re.search(r'([\d,]+)\s*(?:like|reaction)', counts_text, re.IGNORECASE)
if likes_match:
post_data["likes"] = int(likes_match.group(1).replace(",", ""))
comments_match = re.search(r'([\d,]+)\s*comment', counts_text, re.IGNORECASE)
if comments_match:
post_data["comments"] = int(comments_match.group(1).replace(",", ""))
reposts_match = re.search(r'([\d,]+)\s*repost', counts_text, re.IGNORECASE)
if reposts_match:
post_data["reposts"] = int(reposts_match.group(1).replace(",", ""))
except Exception:
pass
# Extract date
try:
time_el = post.query_selector("time")
if not time_el:
time_el = post.query_selector("span.feed-shared-actor__sub-description")
if time_el:
post_data["date"] = time_el.inner_text().strip()
except Exception:
pass
if post_data["text"]: # Only add if we got some content
activities.append(post_data)
except Exception:
continue
except Exception as e:
logger.error(f"Activity scrape failed for {linkedin_url}: {e}")
return activities
# =============================================================================
# COMPANY PAGE SCRAPING
# =============================================================================
def scrape_company_page(page, company_url: str) -> dict:
"""
Visit a LinkedIn company page and extract intelligence.
Returns dict with: size, industry, headquarters, recent_posts,
job_count, new_employees, decision_makers
"""
result = {
"url": company_url,
"name": "",
"size": "",
"industry": "",
"headquarters": "",
"description": "",
"recent_posts": [],
"job_count": 0,
"new_employees": "",
"followers": 0,
}
try:
page.goto(company_url, wait_until="domcontentloaded")
time.sleep(DEFAULT_PAGE_LOAD_WAIT)
_random_scroll(page, scrolls=2)
if _check_for_rate_limit(page):
logger.warning("Rate limit detected during company page scrape")
raise Exception("LinkedIn rate limit detected")
# Company name
try:
name_el = page.query_selector("h1.org-top-card-summary__title")
if name_el:
result["name"] = name_el.inner_text().strip()
except Exception:
pass
# Extract company info from the about section
try:
info_items = page.query_selector_all("dl.overflow-hidden dd")
info_labels = page.query_selector_all("dl.overflow-hidden dt")
for label_el, value_el in zip(info_labels, info_items):
label = label_el.inner_text().strip().lower()
value = value_el.inner_text().strip()
if "industry" in label:
result["industry"] = value
elif "size" in label or "employee" in label:
result["size"] = value
elif "headquarter" in label or "location" in label:
result["headquarters"] = value
except Exception:
pass
# Followers count
try:
followers_el = page.query_selector("div.org-top-card-summary-info-list__info-item")
if followers_el:
text = followers_el.inner_text()
followers_match = re.search(r'([\d,]+)\s*follower', text, re.IGNORECASE)
if followers_match:
result["followers"] = int(followers_match.group(1).replace(",", ""))
except Exception:
pass
# Job openings count
try:
jobs_link = page.query_selector("a[href*='/jobs/']")
if jobs_link:
jobs_text = jobs_link.inner_text()
jobs_match = re.search(r'(\d+)', jobs_text)
if jobs_match:
result["job_count"] = int(jobs_match.group(1))
except Exception:
pass
_increment_usage("company_views")
except Exception as e:
logger.error(f"Company page scrape failed for {company_url}: {e}")
raise
return result
def search_company_people(page, company_name: str, role_keywords: list = None) -> list:
"""
Search for people at a company on LinkedIn, optionally filtering by role.
Returns list of dicts with: name, title, degree, profile_url
"""
results = []
search_query = company_name
if role_keywords:
search_query += " " + " ".join(role_keywords[:2])
search_url = f"https://www.linkedin.com/search/results/people/?keywords={quote_plus(search_query)}"
try:
page.goto(search_url, wait_until="domcontentloaded")
time.sleep(DEFAULT_PAGE_LOAD_WAIT + 1)
_random_scroll(page, scrolls=2)
_increment_usage("searches")
if _check_for_rate_limit(page):
logger.warning("Rate limit detected during people search")
return results
# Find search result items
result_items = page.query_selector_all("li.reusable-search__result-container")
if not result_items:
result_items = page.query_selector_all("div.entity-result")
for item in result_items[:10]:
try:
person = {
"name": "",
"title": "",
"degree": 0,
"profile_url": "",
}
# Name and link
try:
link_el = item.query_selector("a.app-aware-link")
if link_el:
person["name"] = link_el.inner_text().strip().split("\n")[0]
href = link_el.get_attribute("href") or ""
if "/in/" in href:
person["profile_url"] = href.split("?")[0]
except Exception:
pass
# Title
try:
title_el = item.query_selector("div.entity-result__primary-subtitle")
if title_el:
person["title"] = title_el.inner_text().strip()
except Exception:
pass
# Connection degree
try:
badge_el = item.query_selector("span.entity-result__badge-text")
if badge_el:
badge_text = badge_el.inner_text()
degree_match = re.search(r'(\d)', badge_text)
if degree_match:
person["degree"] = int(degree_match.group(1))
except Exception:
pass
if person["name"]:
results.append(person)
except Exception:
continue
except Exception as e:
logger.error(f"Company people search failed for {company_name}: {e}")
return results
# =============================================================================
# FEED INTELLIGENCE
# =============================================================================
def scan_feed_for_signals(page, trigger_keywords: list = None, max_posts: int = 30) -> list:
"""
Scroll the LinkedIn feed and find posts matching trigger keywords.
Returns list of dicts with: author, title, company, snippet,
trigger_keyword, likes, comments, url
"""
if trigger_keywords is None:
trigger_keywords = [
"transformation", "restructuring", "culture change",
"employee experience", "new CEO", "leadership change",
"merger", "acquisition", "wellbeing", "behavioural change",
]
signals = []
try:
page.goto("https://www.linkedin.com/feed/", wait_until="domcontentloaded")
time.sleep(DEFAULT_PAGE_LOAD_WAIT)
posts_checked = 0
# Scroll through feed
for scroll_batch in range(6): # 6 scroll batches
_random_scroll(page, scrolls=3)
time.sleep(random.uniform(1.5, 3.0))
if _check_for_rate_limit(page):
logger.warning("Rate limit detected during feed scan")
break
# Find post elements
post_selectors = [
"div.feed-shared-update-v2",
"div.occludable-update",
]
posts = []
for selector in post_selectors:
posts = page.query_selector_all(selector)
if posts:
break
for post in posts:
if posts_checked >= max_posts:
break
try:
# Extract post text
text = ""
text_el = post.query_selector("span.break-words")
if not text_el:
text_el = post.query_selector("div.feed-shared-text")
if text_el:
text = text_el.inner_text().strip()
if not text:
continue
posts_checked += 1
text_lower = text.lower()
# Check for trigger keywords
matched_keyword = None
for keyword in trigger_keywords:
if keyword.lower() in text_lower:
matched_keyword = keyword
break
if not matched_keyword:
continue
signal = {
"author": "",
"title": "",
"company": "",
"snippet": text[:200],
"trigger_keyword": matched_keyword,
"likes": 0,
"comments": 0,
"url": "",
}
# Extract author info
try:
actor_el = post.query_selector("span.feed-shared-actor__name")
if actor_el:
signal["author"] = actor_el.inner_text().strip().split("\n")[0]
desc_el = post.query_selector("span.feed-shared-actor__description")
if desc_el:
signal["title"] = desc_el.inner_text().strip()
# Try to extract company from title
if signal["title"]:
parts = signal["title"].split(" at ")
if len(parts) > 1:
signal["company"] = parts[-1].strip()
else:
parts = signal["title"].split(" | ")
if len(parts) > 1:
signal["company"] = parts[-1].strip()
except Exception:
pass
# Engagement counts
try:
social_counts = post.query_selector("ul.social-details-social-counts")
if social_counts:
counts_text = social_counts.inner_text()
likes_match = re.search(r'([\d,]+)\s*(?:like|reaction)', counts_text, re.IGNORECASE)
if likes_match:
signal["likes"] = int(likes_match.group(1).replace(",", ""))
comments_match = re.search(r'([\d,]+)\s*comment', counts_text, re.IGNORECASE)
if comments_match:
signal["comments"] = int(comments_match.group(1).replace(",", ""))
except Exception:
pass
signals.append(signal)
except Exception:
continue
if posts_checked >= max_posts:
break
except Exception as e:
logger.error(f"Feed scan failed: {e}")
return signals
# =============================================================================
# LINKEDIN URL RESOLUTION
# =============================================================================
def resolve_linkedin_url(page, name: str, company: str) -> str:
"""
Find a LinkedIn profile URL by searching for name + company.
Results are cached in the linkedin_urls table to avoid re-searching.
Returns profile URL string, or empty string if not found.
"""
_init_url_cache_table()
# Check cache first
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
cursor.execute(
"SELECT linkedin_url FROM linkedin_urls WHERE contact_name = ? AND company = ?",
(name, company or "")
)
row = cursor.fetchone()
conn.close()
if row:
return row[0] or ""
# Search LinkedIn
search_query = f"{name} {company}" if company else name
search_url = f"https://www.linkedin.com/search/results/people/?keywords={quote_plus(search_query)}"
profile_url = ""
try:
page.goto(search_url, wait_until="domcontentloaded")
time.sleep(DEFAULT_PAGE_LOAD_WAIT + 1)
_increment_usage("searches")
if _check_for_rate_limit(page):
logger.warning("Rate limit detected during URL resolution")
return ""
# Find first profile link in search results
# LinkedIn's DOM classes change frequently, so we search broadly
all_links = page.query_selector_all("a")
for link in all_links:
href = link.get_attribute("href") or ""
if "/in/" in href and "linkedin.com" in href:
profile_url = href.split("?")[0]
break
except Exception as e:
error_str = str(e)
logger.error(f"URL resolution failed for {name} at {company}: {e}")
# Don't cache on network errors — retry next run
if any(err in error_str for err in [
"ERR_INTERNET_DISCONNECTED", "ERR_NAME_NOT_RESOLVED",
"ERR_CONNECTION_RESET", "ERR_NETWORK_CHANGED", "Timeout",
]):
raise # Let hunter handle network failures
# Cache result (even empty ones to avoid re-searching)
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
cursor.execute(
"INSERT OR REPLACE INTO linkedin_urls (contact_name, company, linkedin_url, date_resolved) VALUES (?, ?, ?, ?)",
(name, company or "", profile_url, datetime.now().isoformat())
)
conn.commit()
conn.close()
return profile_url
def get_cached_url(name: str, company: str = "") -> str:
"""Get a cached LinkedIn URL without making any web requests."""
_init_url_cache_table()
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
cursor.execute(
"SELECT linkedin_url FROM linkedin_urls WHERE contact_name = ? AND company = ?",
(name, company or "")
)
row = cursor.fetchone()
conn.close()
return row[0] if row and row[0] else ""
# =============================================================================
# HELPER: GET HOT COMPANIES WITH CONNECTIONS
# =============================================================================
def get_hot_companies_with_connections(min_score: int = 50) -> list:
"""
Get top-scoring companies that have network connections.
Uses fuzzy matching to bridge company name differences between
the companies table and network_graph.
Returns list of (company_name, [connection_dicts]) tuples.
"""
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
# Get ALL hot companies (not just those with signals_network)
cursor.execute("""
SELECT c.name, c.overall_score
FROM companies c
WHERE c.overall_score >= ?
ORDER BY c.overall_score DESC
LIMIT 30
""", (min_score,))
companies = cursor.fetchall()
result = []
for company_name, score in companies:
# Build multiple search patterns for fuzzy matching
name_lower = company_name.lower().strip()
# Remove common suffixes for matching
clean_name = re.sub(
r'\s*(utilities|limited|ltd|plc|group|holdings|inc|corp|uk|services|solutions)\s*',
' ', name_lower, flags=re.IGNORECASE
).strip()
# Get first two significant words for broad matching
words = [w for w in clean_name.split() if len(w) > 2]
first_word = words[0] if words else name_lower.split()[0] if name_lower.split() else ""
# Search network_graph with multiple strategies
connections = []
seen_contacts = set()
# Strategy 1: Exact normalized match
cursor.execute("""
SELECT ng.contact_name, ng.company, ng.position, ng.colleague_owner,
ng.date_connected, ng.is_new_company
FROM network_graph ng
WHERE ng.company_normalized = ?
LIMIT 10
""", (clean_name,))
for row in cursor.fetchall():
key = (row[0], row[3]) # (contact_name, colleague)
if key not in seen_contacts:
seen_contacts.add(key)
connections.append({
"contact_name": row[0], "company": row[1],
"position": row[2], "colleague_owner": row[3],
"date_connected": row[4], "is_mover": bool(row[5]),
})
# Strategy 2: LIKE match on first significant word (for cases like
# "Thames Water Utilities" matching "thames water" in network_graph)
if len(connections) < 5 and first_word and len(first_word) >= 4:
cursor.execute("""
SELECT ng.contact_name, ng.company, ng.position, ng.colleague_owner,
ng.date_connected, ng.is_new_company
FROM network_graph ng
WHERE ng.company_normalized LIKE ?
LIMIT 10
""", (f"{first_word}%",))
for row in cursor.fetchall():
key = (row[0], row[3])
if key not in seen_contacts:
seen_contacts.add(key)
connections.append({
"contact_name": row[0], "company": row[1],
"position": row[2], "colleague_owner": row[3],
"date_connected": row[4], "is_mover": bool(row[5]),
})
# Strategy 3: Raw company name contains match
if len(connections) < 5:
cursor.execute("""
SELECT ng.contact_name, ng.company, ng.position, ng.colleague_owner,
ng.date_connected, ng.is_new_company
FROM network_graph ng
WHERE ng.company LIKE ?
LIMIT 10
""", (f"%{company_name}%",))
for row in cursor.fetchall():
key = (row[0], row[3])
if key not in seen_contacts:
seen_contacts.add(key)
connections.append({
"contact_name": row[0], "company": row[1],
"position": row[2], "colleague_owner": row[3],
"date_connected": row[4], "is_mover": bool(row[5]),
})
# Prioritize senior contacts
connections.sort(key=lambda c: (
0 if any(t in (c.get('position', '') or '').lower() for t in
['director', 'head of', 'chief', 'vp', 'vice president', 'ceo', 'cfo', 'coo', 'chro', 'cpo']) else 1,
))
if connections:
result.append((company_name, connections[:5]))
conn.close()
return result
def get_senior_target_contacts(limit: int = 30) -> list:
"""
Get senior contacts from the network who are in HR/People/Culture/
Transformation roles — the people most likely to buy Curium's services.
These are proactively scanned regardless of whether their company
has other signals, because a CHRO or Head of People is always a
valuable relationship to understand.
Returns list of connection dicts.
"""
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
# Target role keywords — people who buy transformation/culture services
role_patterns = [
'%chief people%', '%chief human%', '%chro%',
'%head of people%', '%head of hr%', '%head of human%',
'%director of people%', '%director of hr%', '%director of human%',
'%vp people%', '%vp hr%', '%vp human%',
'%head of transformation%', '%director of transformation%',
'%head of culture%', '%director of culture%',
'%head of organisational%', '%head of organizational%',
'%head of od%', '%director of od%',
'%head of leadership%', '%director of leadership%',
'%head of employee experience%', '%head of engagement%',
'%head of talent%', '%director of talent%',
'%head of change%', '%director of change%',
'%chief culture%', '%chief transformation%',
'%programme director%', '%program director%',
'%head of pmo%', '%pmo director%',
'%chief operating%', '%coo %',
'%head of strategy%', '%director of strategy%',
'%head of digital%', '%director of digital%',
'%head of wellbeing%', '%director of wellbeing%',
]
# Build a big OR query for all target roles
where_clauses = " OR ".join([f"LOWER(ng.position) LIKE ?" for _ in role_patterns])
# Exclude contacts already scanned (in signals_linkedin_intel)
cursor.execute(f"""
SELECT ng.contact_name, ng.company, ng.position, ng.colleague_owner,
ng.date_connected, ng.is_new_company
FROM network_graph ng
WHERE ({where_clauses})
AND ng.company != ''
AND NOT EXISTS (
SELECT 1 FROM signals_linkedin_intel sli
WHERE sli.contact_name = ng.contact_name
AND sli.colleague_name = ng.colleague_owner
)
ORDER BY ng.is_senior DESC, RANDOM()
LIMIT ?
""", (*role_patterns, limit))
contacts = []
for row in cursor.fetchall():
contacts.append({
"contact_name": row[0],
"company": row[1],
"position": row[2],
"colleague_owner": row[3],
"date_connected": row[4],
"is_mover": bool(row[5]),
})
conn.close()
return contacts
def get_movers_for_scan() -> list:
"""
Get contacts who moved companies (is_new_company = 1).
Returns list of connection dicts.
"""
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
cursor.execute("""
SELECT contact_name, company, position, colleague_owner, date_connected
FROM network_graph
WHERE is_new_company = 1
ORDER BY date_imported DESC
LIMIT 20
""")
movers = []
for row in cursor.fetchall():
movers.append({
"contact_name": row[0],
"company": row[1],
"position": row[2],
"colleague_owner": row[3],
"date_connected": row[4],
})
conn.close()
return movers
# =============================================================================
# STANDALONE TEST
# =============================================================================
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="LinkedIn Intelligence Module")
parser.add_argument("--test", action="store_true", help="Run basic test")
parser.add_argument("--setup", action="store_true", help="Setup LinkedIn login")
parser.add_argument("--status", action="store_true", help="Check session status")
parser.add_argument("--limits", action="store_true", help="Show daily limits")
args = parser.parse_args()
if args.status:
status = get_linkedin_session_status()
print(f"LinkedIn session status: {status}")
elif args.limits:
limits = check_daily_limits()
print(f"Daily limits remaining:")
print(f" Profile views: {limits['profile_views']}/{DAILY_LIMITS['profile_views']}")
print(f" Company views: {limits['company_views']}/{DAILY_LIMITS['company_views']}")
print(f" Searches: {limits['searches']}/{DAILY_LIMITS['searches']}")
elif args.setup:
from playwright.sync_api import sync_playwright
print("Opening browser for LinkedIn login...")
print("Please log in manually in the browser window.")
with sync_playwright() as p:
success = setup_linkedin_login(p)
if success:
print("Login successful! Session saved.")
else:
print("Login timed out. Please try again.")
elif args.test:
from playwright.sync_api import sync_playwright
print("Running basic LinkedIn test...")
with sync_playwright() as p:
browser, page = create_linkedin_context(p, headless=False)
if is_logged_in(page):
print("Logged in! Testing feed scan...")
signals = scan_feed_for_signals(page, max_posts=10)
print(f"Found {len(signals)} feed signals")
for s in signals[:3]:
print(f" - {s['author']}: {s['snippet'][:60]}... ({s['trigger_keyword']})")
else:
print("Not logged in. Run --setup first.")
browser.close()
else:
parser.print_help()
"""
LinkedIn Intelligence Module (linkedin_intel.py)
Authenticated LinkedIn scraping via Playwright persistent browser profile.
Uses a real browser session to gather deep intelligence:
- Profile data (title, company, activity, mutual connections)
- Profile activity (posts, engagement, interaction with team)
- Company pages (size, industry, recent hires, decision-makers)
- Feed scanning for transformation trigger keywords
- LinkedIn URL resolution from name + company
Anti-ban strategy:
- Persistent browser profile (login once, reuse cookies)
- Human-like delays (3-8s between page loads)
- Session limits (40 profiles + 10 companies per run)
- Daily caps tracked in SQLite (80 profiles/day, 20 companies/day)
- Random scroll patterns and jitter
- Graceful degradation on rate limiting / CAPTCHA
"""
import os
import re
import time
import random
import sqlite3
import logging
from datetime import datetime, date
from pathlib import Path
from urllib.parse import quote_plus
logger = logging.getLogger(__name__)
PROFILE_DIR = os.path.expanduser("~/.curium-linkedin-profile")
DATABASE = "leads.db"
DAILY_LIMITS = {
"profile_views": 200,
"company_views": 40,
"searches": 30,
}
# Delay settings (overridable from config)
DEFAULT_MIN_DELAY = 3
DEFAULT_MAX_DELAY = 8
DEFAULT_PAGE_LOAD_WAIT = 2
# =============================================================================
# DAILY USAGE TRACKING
# =============================================================================
def _init_usage_table():
"""Create daily usage tracking table if not exists."""
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS linkedin_daily_usage (
id INTEGER PRIMARY KEY AUTOINCREMENT,
usage_date TEXT NOT NULL,
profile_views INTEGER DEFAULT 0,
company_views INTEGER DEFAULT 0,
searches INTEGER DEFAULT 0,
UNIQUE(usage_date)
)
""")
conn.commit()
conn.close()
def _init_url_cache_table():
"""Create LinkedIn URL cache table if not exists."""
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS linkedin_urls (
id INTEGER PRIMARY KEY AUTOINCREMENT,
contact_name TEXT NOT NULL,
company TEXT,
linkedin_url TEXT,
date_resolved TEXT NOT NULL,
UNIQUE(contact_name, company)
)
""")
conn.commit()
conn.close()
def check_daily_limits() -> dict:
"""Check remaining daily quota. Resets at midnight."""
_init_usage_table()
today = date.today().isoformat()
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
cursor.execute(
"SELECT profile_views, company_views, searches FROM linkedin_daily_usage WHERE usage_date = ?",
(today,)
)
row = cursor.fetchone()
conn.close()