goquery-parsing
Builds robust, maintainable Go HTML parsers with goquery — stable CSS selectors, typed structs, and parsers that survive minor markup changes. TRIGGER — load BEFORE writing the parser, not after: raw HTML or a .html file is in context and structured data is wanted out of it; goquery is imported or `Find(`/`Attr(`/`Each(` is being written; the prompt names goquery, scraper, parser, extract, scrape, crawl, or selector alongside HTML or a page. Trigger on plain requests — "pull the prices off this page", "get these fields out of this markup", "turn this listing into structs" — the user will not name goquery; the HTML plus a Go repo is the trigger. SKIP when the extraction target is JSON or an API response rather than markup, or when the project is not Go.
- License 许可
- MIT
- 最近更新
- 2026-11-11
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- goquery-parsing
- description
- Builds robust, maintainable Go HTML parsers with goquery — stable CSS selectors, typed structs, and parsers that survive minor markup changes. TRIGGER — load BEFORE writing the parser, not after: raw HTML or a .html file is in context and structured data is wanted out of it; goquery is imported or `Find(`/`Attr(`/`Each(` is being written; the prompt names goquery, scraper, parser, extract, scrape, crawl, or selector alongside HTML or a page. Trigger on plain requests — "pull the prices off this page", "get these fields out of this markup", "turn this listing into structs" — the user will not name goquery; the HTML plus a Go repo is the trigger. SKIP when the extraction target is JSON or an API response rather than markup, or when the project is not Go.
- allowed-tools
- Read, Write, Edit, Bash(go:*), Bash(gofmt:*), Bash(goimports:*)
02 资源文件 1
- 参考文档references/api.md5.6 KB
03 SKILL.md 正文
goquery-parsing
Generate Go parsers from HTML snapshots. The goal is code that extracts the right data reliably and keeps working when a page gets restyled or minor markup is shuffled.
For the full API method signatures, see references/api.md.
Workflow
- Read the HTML — scan the full snapshot before writing a single selector
- Name the target data — define the Go struct that will hold the output
- Pick stable selectors — see the hierarchy below
- Write the parser — follow the code structure below
- Verify — compile, test against the snapshot, check edge cases
Selector Stability Hierarchy
A selector is only as durable as the thing it targets. From most to least stable:
| Tier | Examples | Why it lasts |
|---|---|---|
| 1 — Semantic data attributes | [data-product-id], [data-testid="price"] |
Set explicitly for machine consumption; survive redesigns |
| 2 — IDs | #main-content, #search-results |
Unique; high cost to change |
| 3 — ARIA / role attributes | [role="main"], [aria-label="price"] |
Accessibility-driven; stable across CSS refactors |
| 4 — Semantic HTML elements | article, time[datetime], address, main, nav |
Tag semantics don't change with styling |
| 5 — Meaningful class names | .product-title, .job-listing, .price-amount |
Component names outlast utility classes |
| 6 — Structural attribute combos | a[href^="/product/"], img[alt], input[name="q"] |
Content-based; not style-dependent |
| 7 — Tag + structure (last resort) | article h2, ul.results > li |
Fragile to layout changes; use only when tiers 1–6 yield nothing |
Avoid:
- Utility/positional classes:
mt-4,flex,col-md-6,text-sm— they change constantly :nth-child()on variable-length lists — inserted ads or banners break the index- Deep descendant chains (more than 3 levels) — brittle to layout refactors
- Chained traversals:
.Next().Next().Find()— index arithmetic dressed as code
When the HTML offers nothing better than tier 7, note it with a comment explaining which attribute to watch for if the page is ever cleaned up.
Code Structure
Define the output struct first
Name the struct after the entity, not the page. Fields should be the minimal set the caller actually needs — leave optional/nullable fields as empty strings rather than pointers unless presence vs absence genuinely matters to the caller.
type Product struct {
Name string
Price string
URL string
ImageURL string
Description string // empty when absent — caller checks len()
}
Parse function signature
Accept io.Reader so the caller controls the source (file, HTTP response, string, test fixture).
Return a descriptive error rather than silently returning an empty slice.
func ParseProducts(r io.Reader) ([]Product, error) {
doc, err := goquery.NewDocumentFromReader(r)
if err != nil {
return nil, fmt.Errorf("parsing HTML: %w", err)
}
var products []Product
doc.Find("[data-product-id]").Each(func(_ int, s *goquery.Selection) {
products = append(products, extractProduct(s))
})
if len(products) == 0 {
return nil, fmt.Errorf("no products found: selector may need updating")
}
return products, nil
}
Extract helpers for repeated patterns
When the same field appears across multiple types, or when a single field needs >1 line to
extract, pull it into a small helper. extractProduct is a receiver-free function that takes
a *goquery.Selection and returns the struct:
func extractProduct(s *goquery.Selection) Product {
return Product{
Name: text(s, "[data-product-name]"),
Price: text(s, ".price-amount"),
URL: s.Find("a[href]").AttrOr("href", ""),
ImageURL: s.Find("img").AttrOr("src", ""),
}
}
// text finds the first matching element and returns trimmed text content.
func text(s *goquery.Selection, selector string) string {
return strings.TrimSpace(s.Find(selector).First().Text())
}
Single-item parsers
When extracting one record from a page (e.g., an article detail), Find().First() returns
a zero-length selection if nothing matched — check with .Length():
func ParseArticle(r io.Reader) (Article, error) {
doc, err := goquery.NewDocumentFromReader(r)
if err != nil {
return Article{}, fmt.Errorf("parsing HTML: %w", err)
}
titleSel := doc.Find("h1[data-article-title], article > h1").First()
if titleSel.Length() == 0 {
return Article{}, fmt.Errorf("article title not found")
}
return Article{
Title: strings.TrimSpace(titleSel.Text()),
Author: text(doc.Selection, "[rel=author]"),
Date: doc.Find("time[datetime]").First().AttrOr("datetime", ""),
Body: extractBody(doc),
}, nil
}
Key Extraction Patterns
Text content
Always strings.TrimSpace() — HTML text nodes typically contain leading/trailing whitespace
and newlines from indentation.
title := strings.TrimSpace(s.Find("h1").Text())
For multi-paragraph body text, collect paragraphs individually:
var paragraphs []string
s.Find("p").Each(func(_ int, p *goquery.Selection) {
if t := strings.TrimSpace(p.Text()); t != "" {
paragraphs = append(paragraphs, t)
}
})
body := strings.Join(paragraphs, "\n\n")
Attributes
Attr returns (string, bool) — use the bool when presence matters:
href, exists := s.Attr("href")
if !exists {
return // skip elements without a link
}
Use AttrOr when absence is acceptable and you have a sensible default:
imgURL := s.Find("img").AttrOr("src", "")
Dates and times
Prefer datetime attribute on <time> elements — it's machine-readable and consistent:
date := doc.Find("time[datetime]").AttrOr("datetime", "")
Fall back to visible text only when datetime is absent.
Links
Resolve relative URLs after extraction — goquery returns raw href values:
href := s.Find("a").AttrOr("href", "")
if href != "" && !strings.HasPrefix(href, "http") {
href = baseURL + href
}
Tables
Row-by-row extraction; skip the header row:
doc.Find("table tbody tr").Each(func(i int, row *goquery.Selection) {
cells := row.Find("td")
if cells.Length() < 3 {
return // malformed row — skip
}
records = append(records, Record{
Name: strings.TrimSpace(cells.Eq(0).Text()),
Value: strings.TrimSpace(cells.Eq(1).Text()),
Date: strings.TrimSpace(cells.Eq(2).Text()),
})
})
Fallback Selectors
When a primary selector is uncertain, chain alternatives with a comma — goquery tries all:
doc.Find("[data-price], .price-amount, .product-price, span.price")
Or try selectors in priority order and take the first that matches:
priceSel := doc.Find("[data-price]")
if priceSel.Length() == 0 {
priceSel = doc.Find(".price-amount")
}
price := strings.TrimSpace(priceSel.First().Text())
Self-Check (minimal test)
Leave a runnable check in a _test.go file that reads the HTML snapshot and asserts the key
fields are non-empty. The test should fail if a future page change breaks the selectors:
func TestParseProducts(t *testing.T) {
f, err := os.Open("testdata/products.html")
if err != nil {
t.Fatal(err)
}
defer f.Close()
got, err := ParseProducts(f)
if err != nil {
t.Fatal(err)
}
if len(got) == 0 {
t.Fatal("expected products, got none")
}
first := got[0]
if first.Name == "" {
t.Error("product name is empty")
}
if first.Price == "" {
t.Error("product price is empty")
}
}
Save the HTML snapshot to testdata/ so the test is self-contained.
Import Block
import (
"fmt"
"io"
"strings"
"github.com/PuerkitoBio/goquery"
)
Common Mistakes
| Mistake | Fix |
|---|---|
.Text() on a multi-element selection |
.First().Text() or .Eq(i).Text() — .Text() on many nodes concatenates all text |
Ignoring Attr bool |
Use AttrOr or check the bool — missing attrs return "" regardless |
| Selector targets a container, not the value | Scope with .Find() inside Each rather than selecting text containers globally |
| Selecting by presentational class | Find a data-* or semantic anchor; note the fragility if none exists |
| Returning empty slice on zero results | Return an error — silent empty is harder to debug than an explicit message |
| Fetching URLs inside the parser | Parser takes io.Reader, caller fetches — keeps the parser testable without HTTP |
04 同仓库更多 Skills
obsidian-develop
Build, prototype, extend, debug and review Obsidian community plugins against a live vault: inspect the running app's UI, DOM, console and plugin state, prototype in the runtime, then verify each change with a build, reload and check loop. Use whenever the user is working on an Obsidian plugin, even when they just say "add a command", "make a sidebar view", "my settings tab is blank", "why isn't my view updating" or "get this ready for the community directory"; when they ask about the plugin API (obsidian.d.ts, Workspace, leaves, Vault, MetadataCache, FileManager, views, modals, settings tabs, CodeMirror 6 editor extensions, markdown post-processors, events); or when they want a running Obsidian instance's DOM, CSS, console or plugins inspected. Not for general note-taking, Obsidian Markdown syntax, themes without a plugin, or managing vault content (use ingest, to-vault or vault-recall for those).
vault-recall
Answer the user's conceptual or technical question using their Obsidian vault as well as general knowledge. Use when the user asks a question (not a task) whose topic appears in the vault MOC digest from session start. Not for task instructions, not mid-task, and not for writing to the vault (that is to-vault).
ingest
Ingest one external source (an article, course lesson, doc, PDF or URL) into the user's Obsidian vault: save the original to raw/, then build wiki/ pages per the vault's § Ingest. Use when the user types /ingest, or says "ingest this", "add this source to my wiki", "put this article/lesson in the vault as a wiki page". Works from any repo. Routing rule: someone else's words go to wiki/ (this skill); the user's own learnings and decisions go to notes/ (/to-vault).
to-tickets
Breaks a source into independently-grabbable GitHub tickets. For a code feature the source is the plan (`docs/plans/<feature>.md`, from /to-plan) and every new or changed symbol lands in exactly one ticket, its signatures copied into the ticket body; a non-code feature is cut from the PRD's slices. Cuts tickets for one feature per run. If a code feature has no approved plan, offers /to-plan instead of cutting from prose. In a repo that runs command-centre, also emits `[[task]]` blocks into its config; in a plain treepad repo, emits a Batch Manifest instead so the tickets materialise as stacked worktrees.
to-seams
Records an agreed-but-unlanded cross-repo interface as a seam: the file a consumer's agent gets pasted into its prompt as ground truth, plus the `[[seam]]` block command-centre reads for the retirement pointer. Use when two repos need to build against an interface neither has landed yet — "record a seam for X", "we agreed on this schema, seam it", "add a seam so Y can build against Z's new field". Halts for approval before writing either file.
to-roadmap
Prioritises settled features into a Now / Next / Later kanban board, rendered as a self-contained ./ideas/roadmap.html. Each card is a feature, not a ticket — one card later becomes several tickets via /to-prd -> /to-plan -> /to-tickets. Boards the features in ./docs/approach.md, or the "## Accepted ideas" in ./ideas/CONTEXT.md when there is no approach doc. The approach doc is settled truth: this assigns tiers and reasons about ordering, it never re-litigates what was decided.