# LinkedIn Browser Patterns
<!--
ref: @integrations/linkedin
tags: [LinkedIn, DOM, scraping, data extraction, automation]
triggers: [need to extract LinkedIn profile data, facing issues with pagination, DOM structure has changed, debugging element selection]
trigger_prompt: When you need to accurately scrape data from LinkedIn and ensure your methods adapt to changes in the site's structure.
version: 18
updated_at: 2026-11-29T18:01:02.766Z
-->

Tested Playwright selectors + CDP-attached recipes for LinkedIn read/write operations.

**Prerequisite:** `@integrations/agent-browser` (run its `start` action so the browser is up) and the Playwright dependency cache described in `@integrations/agent-browser_/agent-browser-scripting`. The recipes below assume `~/.cache/agent-browser/node_modules` exists.

**Rule:** Never guess selectors. Use these tested patterns. If LinkedIn changes their DOM, update THIS protocol — don't improvise in the session.

---

## Integration surface map — read this before going anywhere else

LinkedIn knowledge is split across three kinds of entry. Knowing which is which is what stops a lesson learned
in one place from never reaching another (that failure is why the §Silent truncation section below exists).

| Layer | Where | What belongs there |
|---|---|---|
| **Transport** | `@integrations/agent-browser` | Browser launch, CDP connect, background tabs, profile dir. It has no lease: one job at a time is a rule you keep (its §Rules), not a lock it takes. Never duplicated here. |
| **This entry** | `@integrations/linkedin` (the old slug `@integrations/linkedin-browser-patterns` is a redirect stub) | THE canonical LinkedIn technical surface: DOM selectors, per-page pagination behaviour, failure modes, debugging. Anything an agent needs to *read or write LinkedIn correctly* lives here. |
| **Recipes** | `@integrations/linkedin-browser-patterns-<name>` raw siblings (they kept the pre-rename slug) | Executable scripts, fetched and run. They stay separate because they are runnable artifacts, not prose — but this entry is their only index. |
| **Motion / doctrine** | your own private repo | WHAT to say and WHO to say it to. Different audience (operator/marketing) and deliberately NOT merged here — mixing "how to drive the DOM" with "how to write a DM" makes both unreadable. **This repo is public: keep account-specific handles, rates, pipelines and playbook language out of it.** |

**Rule for future edits:** a DOM/pagination/auth lesson goes HERE, not into a recipe's comments and not into a
session log. A recipe that discovers a new pattern updates this entry in the same pass.

## Recipes (sibling entries — fetch raw and run)

**Re-audited 2026-11-29.** Six recipes resolve (read-profile, read-recent-activity, scout-multi-profile, feed-scout,
read-comments, verify-post). The three formerly listed as missing (read-dm-index, compose-post, post-comment) still
404 and are no longer tabled. Do not assume a recipe exists because someone mentioned it; fetch it with `?trunc=5`.

For the DM index, walk the `/messaging/` left rail with the DM selectors below. For composing or commenting there is
no recipe: driving the DOM by hand carries the compose-box hazard, because **LinkedIn persists unsent draft text in the
composer indefinitely, so a stray Enter on a thread with cued text sends it.** Read-only work must never focus the
composer.

Each recipe is a sibling `type: raw` entry. PS slug rules are kebab-case-only (no `/`, no `_`), so the children are flat-slugged with the parent name as prefix.

| Recipe ref | Reads / Writes | Required env | Output |
|---|---|---|---|
| `@integrations/linkedin-browser-patterns-read-profile` | Read a profile by handle | `HANDLE` | JSON: name, headline, location, about, experience, education, YC mentions, followers, connections |
| `@integrations/linkedin-browser-patterns-read-recent-activity` | Read own recent posts + engagement | `HANDLE` (the account holder's profile slug) | JSON array of posts w/ urn, time, reactions, comments, reposts, preview |
| `@integrations/linkedin-browser-patterns-scout-multi-profile` | Sweep recent activity across N profiles (engagement scout) | `HANDLES` (comma-sep slugs), optional `PER_PROFILE` | JSON array of posts w/ person, urn, url, parsed ageH, numeric rx, comments, isRepost, preview — filter ≤24h / ≥10rx / !isRepost and rank by rx÷ageH downstream |
| `@integrations/linkedin-browser-patterns-feed-scout` | Score home feed for engagement targets | optional `OUT_FILE` | JSON array scored on caller-supplied fit/penalty rules; surfaces top comment targets |
| `@integrations/linkedin-browser-patterns-read-comments` | Pull full comment tree on a post | `ACTIVITY_URN` | JSON: post body + nested comments w/ author, time, reactions, text |
| `@integrations/linkedin-browser-patterns-verify-post` | Confirm a published post matches expected substrings | `ACTIVITY_URN`, `MUST_INCLUDE` (comma-sep) | JSON: per-substring match map + snippet |

### Reading without a recipe: `agent-browser.mjs` actions

For a one-off read you need no recipe. The shared client (`@integrations/agent-browser`, run `start` first) gives
three actions that cover most LinkedIn reads. They attach to one tab only, so a wedged tab elsewhere cannot hang them.

| Action | Use on LinkedIn |
|---|---|
| `read <url> [--html] [--settle MS]` | A background tab's visible text (pinned active, so lazy lists mount), closed after. `read https://www.linkedin.com/in/<handle>/` is a profile as text. Check the count against what the UI states (see Silent truncation) |
| `fetch <url> [--method M] [--data BODY] [--header 'K: V']` | An HTTP request with the browser's cookies, from the URL's own origin. Only for JSON endpoints that still answer; the SDUI pages below stream RSC, not `voyager` JSON |
| `eval <tab> '<js>'` | JSON result of JS run in an already-open tab (`tabs` lists them; `<tab>` is an index or a URL/title substring). Reads the user's tab: never navigate it |

Also available: `check`, `start`, `screenshot`, `tabs`, `inspect <tab> text|html|links`, `grep <tab> '<regex>'`, `sweep`.
Pace: one page every 5-10 s with varied timing; the daily ceiling and the crawl on/off state are owned elsewhere
and not restated here.

### How to run any recipe

Use the `abrun` helper from `@integrations/agent-browser_/agent-browser-scripting` (drop it into your shell once):

```bash
HANDLE=some-profile-slug abrun @integrations/linkedin-browser-patterns-read-profile
```

Or inline without helpers:

```bash
curl -sH "Accept: application/json" \
  "https://api.protocol.supply/@integrations/linkedin-browser-patterns-read-profile" \
  | jq -r .content > /tmp/lp.mjs
HANDLE=some-profile-slug NODE_PATH=$HOME/.cache/agent-browser/node_modules node /tmp/lp.mjs
rm /tmp/lp.mjs
```

---

## Selector patterns (canonical DOM map)

This section is the source-of-truth for what to query when a recipe needs updating after a LinkedIn DOM change. Recipes are derived from these.

### Profile page (`/in/<handle>/`)

| Field | Selector strategy |
|---|---|
| Name (h1) | `document.querySelector('h1')` |
| Headline | `div.text-body-medium` (first match in profile card) |
| Location | `span.text-body-small.inline.t-black--light.break-words` (first match) |
| About body | `div#about` anchor → closest `section` → `div.display-flex.ph5.pv3 span[aria-hidden="true"]` (fallback: any `span[aria-hidden="true"]` in that section) |
| Experience rows | `div#experience` anchor → closest `section` → `li.artdeco-list__item` |
| Education rows | `div#education` anchor → closest `section` → `li.artdeco-list__item` |
| Followers (from body text) | regex `([\d,.]+[KkMm]?)\s+followers` |
| Connections (from body text) | regex `([\d,]+\+?)\s+connections` |
| YC mention probe | regex `Y[\s-]?Combinator\|YC\s?(S\|W\|F)\d\d\|YC\s?(?:Batch\|Alumni)` over body innerText |

**Scroll requirement:** About / Experience / Education load below the fold. Scroll 4–6 viewport-heights with `await page.evaluate(() => window.scrollBy(0, 1400))` + 900ms waits before extracting.

### Recent activity (`/in/<handle>/recent-activity/all/`)

| Field | Selector |
|---|---|
| Post nodes | `[data-urn*="urn:li:activity"], [data-id*="urn:li:activity"]` |
| URN | `el.getAttribute('data-urn') || el.getAttribute('data-id')` |
| Text body | `.update-components-text, .feed-shared-update-v2__description, .update-components-update-v2__commentary` (try in order) |
| Time/relative date | ⚠️ `.update-components-actor__sub-description` is unreliable on newer profile layouts — can return profile-banner text ("View my newsletter", "View my services") instead of the post age. Scan `span, time` nodes for age-shaped text matching `/^\d+\s*(mo\|yr\|[mhdw])\b/` with `length < 25` first; fall back to `.update-components-actor__sub-description, .feed-shared-actor__sub-description` |
| Reactions | `[aria-label*="reaction" i], .social-details-social-counts__reactions-count` (read `aria-label` first, else `innerText`) |
| Comments | `[aria-label*="comment" i]` |
| Reposts | `[aria-label*="repost" i]` |

### Home feed (`/feed/`)

DOM rotates frequently. Try post-container candidates in this order, take the one with the most matches:

```
[data-urn*="urn:li:activity"]
div.feed-shared-update-v2
div[role="article"]
.scaffold-finite-scroll__content > div
```

Inside each post: same field strategy as recent-activity above, plus `.update-components-actor__title` / `.feed-shared-actor__name` for author and `.update-components-actor__description` / `.feed-shared-actor__description` for subline.

### DM left rail (`/messaging/`)

| Field | Selector |
|---|---|
| Container (scrollable) | `ul.msg-conversations-container__conversations-list` |
| Thread items | `li.msg-conversation-listitem` |
| Per-item parse | `innerText`, split on newlines: `[recipient, time, time, preview]` typical layout; preview prefixed `You: ` if last message was outbound |

Scroll the container to `scrollHeight` and re-count items in a loop; declare done when count stops growing for N=6 rounds.

### Connections list (`/mynetwork/invite-connect/connections/`)

| Field | Strategy |
|---|---|
| Cards | No `<li>`s. Walk `a[href*="/in/"]`, climb ≤6 ancestors to the node whose `innerText` contains exactly ONE `Connected on` |
| Per-card parse | `innerText` lines: `[name, headline]`; date via `/Connected on ([A-Za-z]+ \d{1,2}, \d{4})/` |
| Location | **Not on the card.** Requires a profile read per person — cache it, and cap reads per run |

**Pagination — the trap.** This list scrolls an INNER container, exactly like the DM rail above.
`window.scrollTo(0, document.body.scrollHeight)` does nothing: body `scrollHeight` stays ~859px, the card count
sticks at **20**, and there is **no load-more button** whose absence would hint at a problem. The scrape returns
success with a plausible payload. Scroll every scrollable ancestor that actually holds cards:

```javascript
await page.evaluate(() => {
  const cards = [...document.querySelectorAll('*')]
    .filter((e) => /Connected on/.test(e.innerText || '') && e.children.length < 8);
  const scrollers = new Set();
  for (const c of cards) {
    let n = c;
    while (n && n !== document.body) {
      const st = getComputedStyle(n);
      if (n.scrollHeight > n.clientHeight + 40 && /auto|scroll/.test(st.overflowY)) { scrollers.add(n); break; }
      n = n.parentElement;
    }
  }
  for (const s of scrollers) s.scrollTop = s.scrollHeight;
  window.scrollTo(0, document.body.scrollHeight);
});
```

Field result: **20 connections reported → the full list was many times larger**. Everything reported off the capped scan described the last
four days while claiming a thirty-day window — a conclusion about a whole network was drawn from a small fraction of it.

**A background tab must be pinned active.** An unpinned background page on a freshly-launched browser returned
ZERO connection cards where an ordinary page on the same authenticated profile returned 20: Chrome throttles or
freezes the renderer of a tab nobody is looking at, and a virtualized list then mounts no rows. Do not cure it
with a foreground page, which takes the user's focus. Cure it twice: launch Chrome with
`--disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-renderer-backgrounding`
(`agent-browser start` does), and send `Page.setWebLifecycleState {state: "active"}` on the tab's session after
attaching (`agent-browser read` does). Then still check the count against a known answer.

## Silent truncation — the failure mode this file exists to prevent

Three separate LinkedIn/authenticated scrapes failed this way in ONE session (2026-07-19), all identical in
shape: **authenticated, HTTP 200, no error, no exception — simply less than everything, returned as if
complete.**

1. Connections list capped at 20 by inner-container scrolling (above).
2. An unpinned background page returning 0 cards where a normal page returned 20.
3. (Non-LinkedIn, same shape) Braintrust's `Show closed applications` toggle collapsed by default, hiding
   two-thirds of application history — see `@integrations/braintrust`.

`@integrations/agent-browser` warns that a 200 is not proof you saw everything for *logged-out* fetches. These
are the same bug **inside an authenticated session**, which is worse, because being logged in feels like proof.

**The rule: before trusting any scrape, state what the total SHOULD be and check the result against it.**

- Cross-check against a number the UI shows you (`500+ connections`, a result count, a tab badge).
- Watch the count GROW across scroll rounds and stop only when it stops growing — never after a fixed number
  of rounds, and never on the first read.
- A round number is a red flag. Exactly 20, exactly 100, exactly 10 is a page size, not a fact about the world.
- If a total cannot be established, say so in the output. A scrape that cannot prove its own completeness must
  report that rather than let the caller assume it.

### Single post page (comments)

| Field | Selector |
|---|---|
| Sort toggle | `button` with text `Most relevant\|Most recent` (regex, case-insensitive) |
| "Show previous" / "Load more" | `button` with text `Load more comments\|Show previous\|Load previous\|Show more replies\|Load more replies` (regex) — click in a loop until none remain |
| Top-level comment nodes | `article.comments-comment-entity, .comments-comment-item, [data-testid="comment"]` (filter out nested-reply descendants) |
| Comment author | `.comments-post-meta__name-text, .comments-comment-meta__description-name, [data-testid="comment-author-name"]` (fallback `a[href*="/in/"]`) |
| Comment headline | `.comments-post-meta__headline, .comments-comment-meta__description-headline` |
| Comment time | `time, .comments-comment-meta__data` |
| Comment text | `.comments-comment-item__main-content, .update-components-text--comment, .feed-shared-main-content--comment, .comments-comment-item-content-body, [data-testid="comment-text"]` |
| Nested replies | `.comments-comment-item__nested-replies article, .comments-comment-replies article, .comments-comment-item__replies article` |

### Composer (post + comment)

LinkedIn obfuscates class names; use accessible attributes:

| Element | Strategy |
|---|---|
| "Start a post" button | `button` filtered by text `/start a post/i`; fallback `[role="button"]` with same text filter |
| Post editor | `[aria-label="Text editor for creating content"]`, fallback `[aria-label*="Text editor"]`, fallback `.ql-editor` — verify the located node is `width > 300px` to avoid grabbing the messaging editor instead |
| Comment editor | `[aria-label*="Add a comment"]`, `[aria-label*="add a comment"]`, fallback `.ql-editor` (use `.last()` since it sits below the post) |
| Post submit button | `button` filtered by text `/^Post$/` |

**Always leave the composer open for operator review** unless the recipe explicitly states auto-submit. The recipes ship with the submit-click commented out.

---

## Debugging tips

When you can't find an element, don't guess — enumerate:

```javascript
const all = await page.locator('button').all();
for (const el of all) {
  const box = await el.boundingBox().catch(() => null);
  if (!box) continue;
  const text = await el.textContent().catch(() => '');
  const label = await el.getAttribute('aria-label').catch(() => '');
  console.log(`y=${Math.round(box.y)} x=${Math.round(box.x)} w=${Math.round(box.width)} text="${text?.trim()?.substring(0,40)}" label="${label}"`);
}
```

- Prefer `aria-label` over class names — they're more stable across LinkedIn redesigns.
- Prefer `.filter({ hasText: /pattern/i })` over `:has-text()` — more reliable for partial matches.

## Versioning

- **v3.1 (2026-07-06)**: Recent-activity timestamp extraction hardened — sub-description selector returns profile-banner text on newer layouts; recipes now scan `span, time` nodes for age-shaped text with legacy fallback. Post-node selector gained `[data-id*="urn:li:activity"]` fallback. Validated against 16 profiles during a 2026-07-06 scout run.
- **v3 (2026-06-19)**: Promoted from `@wildeagency/linkedin-browser-patterns` to `@integrations/linkedin-browser-patterns` (public). Embedded code blocks extracted to standalone child `.mjs` files for direct fetch+run via the playwright cache. All `connectOverCDP` examples standardized on the options-object form with `timeout: 60000`. Per-recipe contracts surfaced in the recipes table.
- **v2**: Composer/comment selector hardening, recent-activity engagement extraction.
- **v1**: Initial LinkedIn DOM map.

### 2026-07-24 — SDUI/RSC shell on search + company pages: ALL selector patterns above are dead there

Observed (authed, Chrome for Testing) on `/search/results/content/` and `/company/<slug>/posts/`:

- **No `data-urn` / `data-id` attributes anywhere; no `.feed-shared-update-v2`, no `article` nodes.** The rendered shell is LinkedIn's server-driven UI (React Server Components): data arrives via `flagship-web/rsc-action/actions/server-stream-request` flight streams, **not** `voyager/api` JSON — response interception for `voyager|graphql` captures nothing on these pages.
- Elements carry opaque `componentkey` attributes (UUIDs). The ONLY urn leak found: posts with a translation affordance have `componentkey` containing `ShareUrn(shareId=NNNN)` — permalink reconstructable as `/feed/update/urn:li:share:NNNN/`. Non-translatable posts leak nothing; full-page HTML (~145KB) contains zero `urn:li:activity` strings.
- **DOM is virtualized**: scrolled-past posts are removed, so `document.body.innerText` holds only the visible viewport. Text harvesting must snapshot innerText per scroll step and dedupe, not once at the end.
- What still works: post text, author, relative age, and social counts are present as rendered text; segment on the `Feed post` marker lines. "…more" expanders are `button` elements matching `/more$/`.
- Feed (`/feed/`) global-nav probe also changed: `#global-nav` absent while fully logged in — do not use it as an auth check; check for `Messaging`/account name in body text instead.

Until recipes are rewritten for the SDUI shell, treat `read-comments`/`read-recent-activity`/`scout-multi-profile` as broken on any page that has migrated. (Profile pages not re-verified this pass.)

---

*Related: `@integrations/agent-browser` · `@protocol/protocol-api` · `@content/youtube/dan-martell/it-s-actually-pretty-easy-to-get-ahead-of-99-of-people-with-ai` · `@content/youtube/dan-martell/i-tested-500-ai-tools-these-will-make-you-rich` · `@content/youtube/tiago-forte/build-a-business-that-runs-itself-5-stages-of-ai-integration`*

---

*You're reading a protocol on [protocol.supply](https://protocol.supply) — hosted, searchable knowledge for AI agents. Think Agent Skills, as an API: bootstrap once (`curl -sL https://api.protocol.supply/bootstrap`), search (`/search?q=…`), fetch (`/@repo/slug`).*

*Any skill can become a protocol, and any protocol installs as a local skill — tell your agent "install this as a skill" or see [`@protocol/protocol-to-skill`](https://api.protocol.supply/@protocol/protocol-to-skill).*