惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
T
Tenable Blog
D
DataBreaches.Net
GbyAI
GbyAI
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
腾讯CDC
V
Visual Studio Blog
B
Blog
雷峰网
雷峰网
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
I
InfoQ
M
MIT News - Artificial intelligence
有赞技术团队
有赞技术团队
T
Tailwind CSS Blog
The Cloudflare Blog
L
LangChain Blog
MongoDB | Blog
MongoDB | Blog
Vercel News
Vercel News
Cloudbric
Cloudbric
L
Lohrmann on Cybersecurity
博客园 - 司徒正美
T
The Exploit Database - CXSecurity.com
Google DeepMind News
Google DeepMind News
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Attack and Defense Labs
Attack and Defense Labs
Martin Fowler
Martin Fowler
SecWiki News
SecWiki News
T
Threat Research - Cisco Blogs
J
Java Code Geeks
Cyberwarzone
Cyberwarzone
Forbes - Security
Forbes - Security
Spread Privacy
Spread Privacy
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
大猫的无限游戏
大猫的无限游戏
O
OpenAI News
D
Darknet – Hacking Tools, Hacker News & Cyber Security
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Schneier on Security
Schneier on Security
S
Security @ Cisco Blogs
酷 壳 – CoolShell
酷 壳 – CoolShell
The Hacker News
The Hacker News
H
Help Net Security
Y
Y Combinator Blog
C
Cybersecurity and Infrastructure Security Agency CISA
T
Tor Project blog
量子位
U
Unit 42
S
SegmentFault 最新的问题
V
V2EX
D
Docker

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
LinkedIn Scraping with Python: Profiles, Jobs & Company Pages
ZyVOP · 2026-06-03 · via DEV Community

LinkedIn is arguably the most valuable professional database on the internet — hundreds of millions of profiles, millions of job postings, and rich company data all in one place. It's no surprise that data scientists, recruiters, and researchers want to access it programmatically.

But LinkedIn is also the hardest major site to scrape. It uses:

  • Heavy JavaScript rendering — almost no meaningful content is in the initial HTML

  • Session-based authentication — most data is only visible when logged in

  • Aggressive bot detection — including TLS fingerprinting, behavioral analysis, and account-level rate limiting

  • Frequent HTML structure changes — CSS selectors break regularly as LinkedIn updates its frontend

This guide gives you a practical, working approach to scraping LinkedIn in 2025. We'll cover two methods: Playwright (recommended) and an overview of the official API as an alternative.

Legal and ethical notice: LinkedIn's Terms of Service prohibit automated scraping. The hiQ v. LinkedIn lawsuit (which argued that publicly available data could be scraped under the Computer Fraud and Abuse Act) has had complex, ongoing outcomes. This guide is for educational purposes. Before scraping LinkedIn for any commercial purpose, consult a lawyer. For most production use cases, LinkedIn's official API or a licensed data provider is a safer choice.

Why Playwright Over Selenium

Both Playwright and Selenium control a real browser, which is necessary for JavaScript-heavy sites. Playwright has several advantages:

Feature Playwright Selenium
Speed Faster async API Slower
Stealth Better fingerprint control Harder to configure
API quality Modern, intuitive Older, verbose
Browser support Chromium, Firefox, WebKit Chrome, Firefox, Edge
Auto-waiting Built-in smart waits Manual waits required
Community (2025) Rapidly growing Mature but stagnant

For LinkedIn specifically, Playwright with playwright-stealth is the current best option.

Installation

pip install playwright playwright-stealth pandas
playwright install chromium

Enter fullscreen mode Exit fullscreen mode

This downloads the Chromium browser binary that Playwright will control.

Step 1: Saving Your LinkedIn Session (One-Time Setup)

The golden rule for LinkedIn scraping is: never automate the login itself. LinkedIn's login page is heavily monitored and a bot logging in triggers immediate account flags.

Instead, log in manually once in a Playwright browser, save your session cookies to a file, and reuse those cookies for all future scraping sessions.

# save_cookies.py — run this once manually
import json
from playwright.sync_api import sync_playwright

def save_linkedin_session():
    with sync_playwright() as p:
        # Launch a visible (non-headless) browser so you can log in yourself
        browser = p.chromium.launch(headless=False)
        context = browser.new_context(
            user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                       "AppleWebKit/537.36 (KHTML, like Gecko) "
                       "Chrome/120.0.0.0 Safari/537.36",
            viewport={"width": 1280, "height": 800}
        )

        page = context.new_page()
        page.goto("https://www.linkedin.com/login")

        # Wait for you to log in manually — you have 60 seconds
        print("Please log in to LinkedIn in the browser window...")
        print("The script will continue once you're on the home feed.")

        # Wait until the feed appears — this confirms a successful login
        page.wait_for_url("**/feed/**", timeout=60000)
        print("Login detected! Saving cookies...")

        cookies = context.cookies()
        with open("linkedin_cookies.json", "w") as f:
            json.dump(cookies, f, indent=2)

        print(f"Saved {len(cookies)} cookies to linkedin_cookies.json")
        browser.close()

save_linkedin_session()

Enter fullscreen mode Exit fullscreen mode

Run this script once, log in manually, and your cookies are saved. These cookies typically stay valid for weeks before LinkedIn requires re-authentication.

Step 2: Loading Your Session in Future Scrapes

import json
from playwright.sync_api import sync_playwright

def create_linkedin_context(playwright):
    """Create a browser context pre-loaded with your saved LinkedIn cookies."""
    browser = playwright.chromium.launch(
        headless=True,  # Can run headless once cookies are saved
        args=[
            "--no-sandbox",
            "--disable-blink-features=AutomationControlled",
        ]
    )

    context = browser.new_context(
        user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                   "AppleWebKit/537.36 (KHTML, like Gecko) "
                   "Chrome/120.0.0.0 Safari/537.36",
        viewport={"width": 1280, "height": 900},
        locale="en-US",
        timezone_id="America/New_York"
    )

    # Load saved cookies
    with open("linkedin_cookies.json") as f:
        cookies = json.load(f)
    context.add_cookies(cookies)

    return browser, context

Enter fullscreen mode Exit fullscreen mode

Step 3: Applying Stealth Mode

Without stealth patches, Playwright exposes dozens of signals that LinkedIn can use to identify it as a bot. The playwright-stealth package patches the most important ones:

from playwright_stealth import stealth_sync

def create_stealthy_page(context):
    """Create a page with stealth patches applied."""
    page = context.new_page()

    # Apply stealth — patches navigator.webdriver, plugins, languages, etc.
    stealth_sync(page)

    return page

Enter fullscreen mode Exit fullscreen mode

The key things stealth patches:

  • navigator.webdriver → set to undefined (normally true in automation)

  • navigator.plugins → adds realistic fake plugins

  • navigator.languages → set to ["en-US", "en"]

  • window.chrome → adds the Chrome runtime object

  • Canvas fingerprinting → adds slight noise to prevent fingerprint matching

Scraping LinkedIn Profiles

A LinkedIn profile URL looks like: https://www.linkedin.com/in/username

import time
import random
import json
from playwright.sync_api import sync_playwright
from playwright_stealth import stealth_sync

def human_delay(min_sec=1.5, max_sec=4.0):
    """Random delay to mimic human browsing behavior."""
    time.sleep(random.uniform(min_sec, max_sec))

def scroll_to_load(page, scrolls=5):
    """Scroll down the page to trigger lazy-loaded sections."""
    for _ in range(scrolls):
        page.evaluate("window.scrollBy(0, window.innerHeight * 0.8)")
        time.sleep(random.uniform(0.8, 1.5))

def scrape_profile(page, profile_url):
    """Extract structured data from a LinkedIn profile page."""
    page.goto(profile_url, wait_until="domcontentloaded")
    human_delay(2, 3.5)

    # Scroll to load experience, education, and skills sections
    scroll_to_load(page, scrolls=6)
    human_delay(1, 2)

    data = {}

    # --- Basic Info ---
    try:
        data["name"] = page.query_selector("h1").inner_text().strip()
    except:
        data["name"] = None

    try:
        data["headline"] = page.query_selector(
            ".text-body-medium.break-words"
        ).inner_text().strip()
    except:
        data["headline"] = None

    try:
        data["location"] = page.query_selector(
            ".text-body-small.inline.t-black--light.break-words"
        ).inner_text().strip()
    except:
        data["location"] = None

    # --- About Section ---
    try:
        about_el = page.query_selector("#about ~ div .full-width")
        data["about"] = about_el.inner_text().strip() if about_el else None
    except:
        data["about"] = None

    # --- Experience ---
    data["experience"] = []
    try:
        exp_items = page.query_selector_all(
            "#experience ~ div li.artdeco-list__item"
        )
        for item in exp_items:
            title_el = item.query_selector(".t-bold span")
            company_el = item.query_selector(".t-14.t-normal span")
            duration_el = item.query_selector(".t-14.t-normal.t-black--light span")

            data["experience"].append({
                "title": title_el.inner_text().strip() if title_el else None,
                "company": company_el.inner_text().strip() if company_el else None,
                "duration": duration_el.inner_text().strip() if duration_el else None,
            })
    except:
        pass

    # --- Education ---
    data["education"] = []
    try:
        edu_items = page.query_selector_all(
            "#education ~ div li.artdeco-list__item"
        )
        for item in edu_items:
            school_el = item.query_selector(".t-bold span")
            degree_el = item.query_selector(".t-14.t-normal span")

            data["education"].append({
                "school": school_el.inner_text().strip() if school_el else None,
                "degree": degree_el.inner_text().strip() if degree_el else None,
            })
    except:
        pass

    # --- Skills ---
    data["skills"] = []
    try:
        skill_els = page.query_selector_all(
            "#skills ~ div .t-bold span[aria-hidden='true']"
        )
        data["skills"] = [el.inner_text().strip() for el in skill_els[:20]]
    except:
        pass

    data["profile_url"] = profile_url
    return data

# Main execution
def main():
    profile_urls = [
        "https://www.linkedin.com/in/some-public-profile/",
        # Add more profile URLs here
    ]

    results = []

    with sync_playwright() as p:
        browser, context = create_linkedin_context(p)
        page = create_stealthy_page(context)

        for i, url in enumerate(profile_urls):
            print(f"[{i+1}/{len(profile_urls)}] Scraping: {url}")
            profile_data = scrape_profile(page, url)
            results.append(profile_data)
            human_delay(3, 6)  # longer delay between profiles

        browser.close()

    # Save results
    with open("profiles.json", "w") as f:
        json.dump(results, f, indent=2, ensure_ascii=False)

    print(f"Saved {len(results)} profiles to profiles.json")

if __name__ == "__main__":
    main()

Enter fullscreen mode Exit fullscreen mode

Scraping LinkedIn Job Listings

Job listings are slightly easier to scrape than profiles because they are available without being logged in (for most searches). Here is a dedicated job scraper:

import time
import random
import pandas as pd
from playwright.sync_api import sync_playwright
from playwright_stealth import stealth_sync

def scrape_linkedin_jobs(keywords, location, num_pages=5):
    """
    Scrape LinkedIn job listings for given keywords and location.

    Args:
        keywords: Job search term, e.g. "python developer"
        location: Location string, e.g. "India"
        num_pages: How many pages to scrape (25 jobs per page)
    """
    base_url = (
        "https://www.linkedin.com/jobs/search/"
        f"?keywords={keywords.replace(' ', '%20')}"
        f"&location={location.replace(' ', '%20')}"
        f"&start={{}}"
    )

    all_jobs = []

    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        context = browser.new_context(
            user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120"
        )
        page = context.new_page()
        stealth_sync(page)

        for page_num in range(num_pages):
            start = page_num * 25
            url = base_url.format(start)
            print(f"Scraping page {page_num + 1}: {url}")

            page.goto(url, wait_until="domcontentloaded")
            time.sleep(random.uniform(2, 4))

            # Scroll to load all job cards
            for _ in range(3):
                page.evaluate("window.scrollTo(0, document.body.scrollHeight)")
                time.sleep(1)

            job_cards = page.query_selector_all(".jobs-search__results-list li")

            for card in job_cards:
                try:
                    title = card.query_selector(
                        ".base-search-card__title"
                    ).inner_text().strip()
                    company = card.query_selector(
                        ".base-search-card__subtitle"
                    ).inner_text().strip()
                    location_el = card.query_selector(
                        ".job-search-card__location"
                    )
                    job_location = location_el.inner_text().strip() if location_el else ""
                    link = card.query_selector("a.base-card__full-link")
                    job_url = link.get_attribute("href") if link else ""
                    date_el = card.query_selector("time")
                    posted_date = date_el.get_attribute("datetime") if date_el else ""

                    all_jobs.append({
                        "title": title,
                        "company": company,
                        "location": job_location,
                        "posted_date": posted_date,
                        "url": job_url
                    })
                except Exception as e:
                    continue  # Skip malformed cards

            time.sleep(random.uniform(2, 5))

        browser.close()

    df = pd.DataFrame(all_jobs).drop_duplicates(subset=["url"])
    return df

# Run
df = scrape_linkedin_jobs("python developer", "India", num_pages=4)
df.to_csv("linkedin_jobs.csv", index=False)
print(f"Scraped {len(df)} unique job listings")
print(df[["title", "company", "location"]].head(10))

Enter fullscreen mode Exit fullscreen mode

Scraping Company Pages

Company pages contain employee count, industry, headquarters location, and a "People" section showing employees.

def scrape_company_page(page, company_url):
    """Extract data from a LinkedIn company page."""
    page.goto(company_url, wait_until="domcontentloaded")
    time.sleep(random.uniform(2, 4))

    # Scroll to load all sections
    page.evaluate("window.scrollTo(0, document.body.scrollHeight)")
    time.sleep(2)

    data = {"url": company_url}

    # Company name
    try:
        data["name"] = page.query_selector("h1").inner_text().strip()
    except:
        data["name"] = None

    # Tagline / description
    try:
        data["tagline"] = page.query_selector(
            ".org-top-card-summary__tagline"
        ).inner_text().strip()
    except:
        data["tagline"] = None

    # Overview stats (employees, industry, HQ, type)
    data["overview"] = {}
    try:
        overview_items = page.query_selector_all(
            ".org-about-module__margin-bottom"
        )
        for item in overview_items:
            label_el = item.query_selector("dt")
            value_el = item.query_selector("dd")
            if label_el and value_el:
                label = label_el.inner_text().strip()
                value = value_el.inner_text().strip()
                data["overview"][label] = value
    except:
        pass

    # Number of followers
    try:
        followers_el = page.query_selector(
            ".org-top-card-summary-info-list__info-item"
        )
        data["followers"] = followers_el.inner_text().strip() if followers_el else None
    except:
        data["followers"] = None

    return data

Enter fullscreen mode Exit fullscreen mode

Rate Limiting and Account Safety

LinkedIn can permanently ban accounts that scrape aggressively. Follow these guidelines to minimize risk:

Delays between requests:

# Conservative — for accounts you care about
time.sleep(random.uniform(5, 12))

# Moderate
time.sleep(random.uniform(2, 5))

# Risky — only for throwaway accounts
time.sleep(random.uniform(0.5, 1.5))

Enter fullscreen mode Exit fullscreen mode

Daily limits to stay safe:

  • Profile views: under 80–100 per day (LinkedIn counts these)

  • Job page loads: under 200 per day

  • Company pages: under 50 per day

Use a dedicated scraping account: Never scrape with your main personal LinkedIn account. Create a separate account specifically for scraping. If it gets banned, your real professional presence is unaffected.

Rotate your session:

import random

def get_random_user_agent():
    agents = [
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0.0.0",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Chrome/119.0.0.0",
        "Mozilla/5.0 (X11; Linux x86_64) Chrome/118.0.0.0",
    ]
    return random.choice(agents)

Enter fullscreen mode Exit fullscreen mode

The Better Alternative: LinkedIn's Official API

For production use, LinkedIn's official API is more reliable and legally sound. LinkedIn offers:

  • LinkedIn Marketing API — for ad data and company insights

  • LinkedIn Sign In with LinkedIn — OAuth-based profile data access

  • LinkedIn Learning API — for course and learning data

  • LinkedIn Talent Insights — paid enterprise product for HR analytics

Apply at: developer.linkedin.com

For bulk data, licensed data providers like People Data Labs, Clearbit, and Apollo.io aggregate LinkedIn data legally and expose it via clean APIs.

Debugging Common LinkedIn Scraping Issues

Issue: Page loads but the data isn't there LinkedIn lazy-loads content. Always scroll the page before extracting:

page.evaluate("window.scrollTo(0, document.body.scrollHeight)")
time.sleep(2)

Enter fullscreen mode Exit fullscreen mode

Issue: Redirected to login page Your cookies have expired. Re-run save_cookies.py and log in again.

Issue: "Hmm, something went wrong" screen LinkedIn detected automation. Reduce speed, use stealth mode, and add more human-like interactions.

Issue: Getting empty strings from selectors LinkedIn frequently changes its CSS classes. Inspect the current page in DevTools and update your selectors. Using XPath is sometimes more stable than class-based CSS selectors.

# XPath is often more robust for LinkedIn
name = page.query_selector("xpath=//h1[contains(@class, 'top-card')]")

Enter fullscreen mode Exit fullscreen mode

Full Pipeline: Scrape, Save, and Analyse

import json
import pandas as pd
from playwright.sync_api import sync_playwright
from playwright_stealth import stealth_sync

def run_pipeline(profile_urls):
    results = []

    with sync_playwright() as p:
        browser, context = create_linkedin_context(p)
        page = create_stealthy_page(context)

        for i, url in enumerate(profile_urls):
            print(f"[{i+1}/{len(profile_urls)}] {url}")
            try:
                data = scrape_profile(page, url)
                results.append(data)
            except Exception as e:
                print(f"  Error: {e}")
                results.append({"profile_url": url, "error": str(e)})

            human_delay(4, 8)

        browser.close()

    # Save raw JSON
    with open("profiles_raw.json", "w") as f:
        json.dump(results, f, indent=2, ensure_ascii=False)

    # Flatten to DataFrame (ignoring nested lists for CSV)
    flat = []
    for r in results:
        flat.append({
            "name": r.get("name"),
            "headline": r.get("headline"),
            "location": r.get("location"),
            "about": r.get("about"),
            "experience_count": len(r.get("experience", [])),
            "first_role": r.get("experience", [{}])[0].get("title") if r.get("experience") else None,
            "first_company": r.get("experience", [{}])[0].get("company") if r.get("experience") else None,
            "skills_count": len(r.get("skills", [])),
            "top_skill": r.get("skills", [None])[0],
            "url": r.get("profile_url")
        })

    df = pd.DataFrame(flat)
    df.to_csv("profiles_summary.csv", index=False)
    print(f"\nSaved {len(df)} profiles.")
    print(df[["name", "headline", "first_company"]].head())
    return df

# Run it
urls = [
    "https://www.linkedin.com/in/example-profile-1/",
    "https://www.linkedin.com/in/example-profile-2/",
]
df = run_pipeline(urls)

Enter fullscreen mode Exit fullscreen mode

Summary

Topic Key takeaway
Authentication Never automate login — save and reuse cookies
Stealth Use playwright-stealth to patch 30+ bot signals
Delays Random delays between 3–8 seconds between profiles
Profiles Scroll to load, extract name/headline/experience/education
Jobs Available without login, 25 per page
Company pages Rich overview stats available in org-about-module
Account safety Use a dedicated scraping account, stay under 100 profiles/day
Best alternative LinkedIn API or licensed data providers for production

Originally published on ZyVOP