When I started writing crawlers, I asked Gemini which language to use, then followed up: “so python has most extensive support on libraries?” It recommended Python. I later built prototypes in Python, Node.js and Go. Looking back, before choosing a language I should have asked what jobs the crawler actually needed to do.
This article covers public pages and data APIs that permit automated access. Suppose we're collecting community event notices. A notice may appear in both “This week's events” and “Family activities.” Some notices need JavaScript to display the body, and collection can stop before a database write. These three problems call for a link queue, fetching in stages and recoverable writes.
A small crawler can start as one function: give it a URL, download the page, read fields and save the result. Once it covers a whole section, discovery produces candidate URLs, the queue remembers outstanding work, the downloader controls how requests go out, content detection decides whether a browser is worth starting, and extraction and storage turn pages into reusable records. Scrapy and Crawlee can take over several of those steps. 12
Resource discovery: follow existing links, but when do you need to scan for resources?
The simplest starting point is a known list of URLs. For a whole section, it usually becomes a listing page, sitemap or pagination cursor in a public API. For every discovered link I record its source and role on the page. “Next page” leads to more links, while a notice title leads to details. Both pages might return 200 and both URLs might end in .html.
In Scrapy, the difference is which callback receives the response. Suppose .notices marks the notice list and rel="next" marks pagination. The selectors are illustrative, but the division between callbacks is reusable.
def parse(self, response):
for href in response.css(".notices a::attr(href)").getall():
yield response.follow(href, callback=self.parse_notice)
next_page = response.css('a[rel="next"]::attr(href)').get()
if next_page:
yield response.follow(next_page, callback=self.parse)
You can also predict resource addresses from an observed pattern. Actively looking for candidates this way is resource scanning. Here “heuristic” means using an empirical rule to select candidates. It cannot prove a resource exists. My experiment began with an observation: notices on nearby dates sometimes had nearby IDs. A later Node prototype constructed different section/date combinations for one ID, generating 3,699 candidate request objects for that ID alone. That's the number generated in code. How many actually went out also depended on queue deduplication and other factors.
For a section with a public directory, I would follow the supplied links first. To test whether prediction adds value, hold out part of a known list and see how many items each method recovers under the same request budget and which additional verifiable notices prediction finds. Several empty candidates in a row show only that those guesses were wrong. They cannot establish complete coverage of a date range.
Link queues: if an address appears twice, should it be revisited after a restart?
A queue item says what to do with a link. If listing pages A and B both point to detail C, enqueue C on first discovery and retain the second source when it appears again. In the same run C needs only one download. Periodic collection must allow listing pages to be revisited, or deduplication will also block the next day's new notices.
A prototype of mine had a subtler bug. It selected every a[href] in a list, resolved relative addresses and filtered by section path. It excluded links containing index.html. The problem was on page two: index_2.html belonged to the same listing but did not contain the string index.html. It went to the detail parser, which still emitted a row for a page without a body container and filled in No content found.
Grouping the old export by full URL and page type reveals the effects of deduplication and link classification separately. 3
| Page type in this export | Exported rows | Distinct URLs | What was actually saved |
|---|---|---|---|
| Notice detail path | 1,990 | 1,990 | Title, ID, publication date and body all populated |
| Section pagination path | 791 | 198 | All were index_number.html, with empty titles and placeholder bodies |
| Total | 2,781 | 2,188 | All 593 duplicate rows came from pagination |
Deduplicating by URL alone removes 593 rows but still treats 198 listing pages as notices. Conversely, even if each valid detail was written once, 1,990 only tells us the fields were nonempty. Coverage also needs an independent list as its denominator.
Resuming after interruption requires two kinds of state. The task queue tracks pending, in-progress and completed work. The results table tracks notices actually written. With rendering as a fallback, the HTTP fetch and browser fetch for one URL are separate tasks. Use two queues or include the stage in the task deduplication key. Both routes ultimately lead to one business record. Scrapy's JOBDIR can restore queued requests and deduplication state when the same job resumes after a clean pause. Crawlee's RequestQueue can distinguish tasks by uniqueKey. 45
My Node version read stored IDs from SQLite on startup, but when handling details it added the ID to an in-memory hits set before waiting for the write. After a failed write, a retry could be skipped because of that set. A more reliable order is to write using a stable business key and acknowledge the task only after commit. If the process exits between the two steps, redelivery updates the same record. The key depends on the source: use ID alone only after verifying it is unique across sections. Otherwise include distinctions such as source and section.
Downloader: who handles concurrency, retries and egress IPs?
The queue decides which task is next. The downloader decides how to send it. Concurrency counts requests in flight at one instant. Rate counts requests sent in a time interval. Faster responses can mean a higher rate at the same concurrency. Scrapy can limit concurrency by domain, pace requests with a download delay, or let AutoThrottle adjust the delay according to response latency. On 429, wait for the site's Retry-After if supplied, and lower the subsequent rate to that site. 67
If a deployment has multiple approved network exits, selecting and rotating egress IPs also belongs in the download layer. For example, an organization requiring designated outbound proxies can have download middleware select an exit consistently and record where connections fail. I count requests per destination site so all exits share a single request budget. Collection of this kind can start with a single exit. 8
I asked Cursor to move the logic into Scrapy and followed up with “when do we really need downloader”. One version called requests.get() directly and constructed a Scrapy HtmlResponse from the response bytes. This allowed the field extraction code to reuse response.css(). But by then the function had already downloaded the response. The framework never saw a pending request and couldn't schedule download concurrency, retries or latency-based throttling for it. Synchronous requests also occupy the calling thread. 16
A backup version took a third route: reuse connections with an aiohttp ClientSession and limit active downloads with a semaphore. But it first listed every candidate URL, created an asynchronous task per address and accumulated the extracted results in another list. Even with few active downloads, the number of tasks waiting in memory grew with the total number of candidates. This is manageable for a small batch of known URLs in order. For a section that expands during discovery, it's easier to let a scheduler pull tasks as needed. 4
The download stage also needs to retain where an error happened. I investigated a Scrapy TLS handshake error, bad ecpoint. If the connection hasn't been established, there's no HTTP status or body to classify. The Requests version used for comparison had certificate verification disabled, so “one downloads and the other errors” was insufficient to identify the cause. Such failures need diagnosis in the download layer.
Fetching in stages: how do you detect a complete body, and when should Playwright take over?
I'd fetch a sample the cheapest way first: read structured fields from a public JSON API if available, otherwise read the raw HTML returned by HTTP. If the browser displays text absent from the response, open the Network panel in developer tools and check whether it arrived via a later Fetch/XHR request. Scrapy's documentation advises: “find the data source and extract the data from it.” A body available through a public API avoids the expense of rendering every page. 9
Define what counts as having the body. For notices with a stable template, start with rules: recognize the detail template, check the content area for nonempty paragraphs, valid tables or body attachments, and verify required fields such as title and publication date. A notice containing only a table may be very short. A navigation page may have thousands of characters. Length alone misclassifies both. For unfamiliar templates, a model could classify them as “body present,” “possibly awaiting rendering,” “wrong page type” or “undetermined,” citing page excerpts that support the decision. Model classification is an optional design. The prototype used selectors and field rules.
| What the HTTP fetch shows | What to do |
|---|---|
| Listing page with next-page and detail links | Return it to link discovery. The 198 pagination URLs mistakenly collected earlier should have branched off here. |
| Detail body and required fields present | Extract directly. If the title includes the ID or table columns are displaced, fix the rules and reparse the saved response. |
| Detail shows a loading placeholder or content appears only after interaction | Check the public data source first. Only enqueue for Playwright if rendering is required. Wait for target text, table rows or attachments, then apply the same acceptance criteria. |
| Link returns 404 | Record that the resource was not found on this visit and end the task. |
| Fields still missing after one render, or the model cannot decide | Save the input and reason for review. Escalate a task at most once to avoid cycling the same failure between layers. |
The local Playwright prototype reused a browser and context, opening one tab for each of two detail URLs. A separate Crawlee browser version checked for 404 and then waited for .div-content. If the container starts empty, waiting for its appearance is too early. Wait until the target fields inside it are ready. HTTP concurrency and simultaneous tab count deserve separate settings. For acceptance I'd count two things: how many directly parseable pages needlessly went to rendering, and how many bodies escalation actually recovered. 10
Why did an event schedule lose its rows and columns in Markdown? Was the SQLite write at fault?
I first fixed title and ID extraction, then wanted to preserve tables in the body. Reading bodies in SQLite later, I found the Markdown table separator gone. At what point had it disappeared? Had writing changed the string, or were rows and columns already lost during HTML-to-Markdown conversion?
I aligned the smaller line-delimited JSON export in the Node directory with SQLite by URL. All 15 URLs were in the database, and all 15 bodies matched character for character. To see what happened before the write, I made a community event schedule and passed the same HTML through the original project's two converters. 11
<div class="div-title">周末活动<p>编号 S01</p></div>
<div class="div-content"><table>
<tr><th>活动</th><th>场地</th></tr>
<tr><td>读书会</td><td>阅览室</td></tr>
<tr><td>观星</td><td>露台</td></tr>
</table></div>
| Prototype extraction method | Actual output for the same input | Effect on notice fields |
|---|---|---|
Scrapy .div-title::text takes the first direct text node | 周末活动 (weekend events) | The ID can be saved separately. Adjust the selector if the title itself is wrapped in a child element. |
Cheerio $('.div-title').first().text() | 周末活动编号 S01 (weekend events, ID S01) | Includes child text, mixing the ID into the title. Both titles are nonempty but mean different things. |
| Python html2text with tables preserved | Header, separator row and both data rows remain, with the two cells in each row separated by a pipe | You can read that the book club meets in the reading room and stargazing takes place on the terrace. |
| Node with default Turndown | Outputs “event, venue, book club, reading room, stargazing, terrace” in order with blank lines between items | All the words remain, but their row and column relationships are gone. Turndown supports a GFM table plugin, which the prototype did not enable. 12 |
This changes the acceptance criteria. Both outputs pass content.length > 0. To search activities by venue, I'd read HTML cells row by row, saving each event and its venue together as one record, and save Markdown separately for people to read. Tables with row or column spans need separate samples. This simple two-column result covers ordinary headers and data rows only.
I switched the Node output from line-delimited JSON to SQLite through Sequelize. On startup it read saved IDs, then called upsert by primary key during processing (update an existing key, insert otherwise). The main local database has 146 records, 146 distinct URLs across six sections. That shows records were written. Those URLs have no overlap with the 1,990 URLs with content in the root-directory JSON, so the two row counts cannot compare Node's and Python's retrieval rates. 3 For why I considered Sequelize and how I chose between local SQLite and the production database, see How should a Node.js project choose an ORM?.
File export also provided a counterexample. results2.json is unreadable as a single JSON document, but decoding at each boundary yields 31 adjacent arrays. The first has eight items and the rest are empty. For appendable run records, I'd use JSON Lines, one object per line. I'd export one complete array separately for bulk exchange. A later multiprocessing version assigned each process a queue directory, but several processes could still submit the same notice at once. SQLite allows only one write transaction at a time. More ORM connections cannot commit in parallel. On one machine, multiple download tasks can hand records to a single writer. 1314
How should you choose between a small script, a crawler framework and a browser?
For a one-off run on known addresses, start with a download library and parser. Once requirements include “continue tomorrow,” “the same notice appears in two sections” or “resume writing after an interruption,” a framework with a persistent queue becomes worthwhile. A browser can work with either approach.
| Approach | What it does for me | When it pays off and where costs appear |
|---|---|---|
| Python · Requests + Beautiful Soup | Downloads HTTP responses and reads HTML with CSS selectors. A public JSON API allows direct field access. 1516 | Easy to debug page by page for a few known URLs and a one-off export. Pagination, rate limits, checkpoints and retries need separate work. If many independent requests are simply waiting for responses, consider reusing an asynchronous HTTPX client first. 17 |
| Python · Scrapy | The spider yields requests or records. The scheduler manages requests, the downloader fetches responses and the exporter writes results. JOBDIR can persist pending requests and deduplication state for the same job. 14 | A good fit for continually updated sections and stable detail rules. You still handle page classification, rendering and business keys. HTTP requests sent manually inside a callback bypass the framework's download management. |
| Node.js · Crawlee + Cheerio | CheerioCrawler gets HTML over HTTP and selects fields with $. RequestQueue deduplicates by uniqueKey. Pages needing a browser can go to the same ecosystem's PlaywrightCrawler. 25 | Reuse existing TypeScript, HTML conversion code or database models from the same project. Agree on field semantics for the HTTP and browser paths. |
| Browser · Playwright, Puppeteer, Selenium | Click, paginate, wait for specific elements and read the page after scripts run. Playwright can open multiple tabs in a browser context. 1018 | Pay the installation and runtime costs when interaction on the page is required. Existing Puppeteer scripts or Selenium WebDriver infrastructure can be reused. I used Playwright in this experiment. |
| Go · Colly + goquery | A Collector manages downloads and callbacks. goquery extracts fields from response HTML. 19 | The callback model integrates directly when the collector deploys with a Go service. The local prototype got as far as writing individual JSON records, but still used a placeholder host and had no result file in its directory. It cannot establish a speed ranking for Go. |
From these experiments I'd choose Scrapy to manage listing and detail requests, parse raw responses directly, and send only templates demonstrably needing rendering to Playwright. The old samples exposed two concrete defects, pagination misclassified as details and lost table structure. Both can be reproduced offline from saved links and HTML. With an existing Node.js service, I'd keep Crawlee + Cheerio and the existing SQLite write path and first add tests for title boundaries and table conversion. The Colly prototype stopped at callbacks and file output. My history showed visits to ScrapeGraphAI and Firecrawl but no results for the same notices. For many heterogeneous templates in the future, the same manually verified pages could test per-page cost, field accuracy and traceability to source for model extraction or hosted collection. 20
I'd use the following minimal comparisons to decide whether a change of implementation is worthwhile. They also work as initial acceptance tests and can be reused after a site redesign.
| Decision | Fixed input and comparison | Result that changes the choice |
|---|---|---|
| Is HTTP enough, and can rules or a model classify correctly? | Fix known detail, pagination and delayed-loading samples and save their raw responses. Manually label which need rendering. Compare the classifications, recording unnecessary and missed escalations, fields completed in each path and time per notice. | Send only templates that a browser alone can complete to rendering. Then compare browser time per valid notice and peak memory. |
| Are extraction rules reliable? | Manually label titles, IDs, dates and at least one schedule. Check each event against its correct venue. | A title containing an ID or rows paired with the wrong columns fails that field, even with status 200 and a long body. |
| Can it recover from interruption? | Use the same known links, interrupt before and after the database write, restart twice and compare the expected notice set, final row count and content. | For missing items, check when completion is recorded. For duplicates, check the business uniqueness key. Then decide if storage needs changing. |
| Does more concurrency help? | Fix samples, hardware and per-site request limits. Record download waits, parsing and writes separately. Compare distinct notices passing field validation divided by total time, reporting failures, retries and peak memory as well. | Tune tab count if the browser consumes the time, the database if writes are queuing. The old experiments lacked same-input timings, so I wouldn't use them to rank throughput across the three languages. |
Footnotes
-
Scrapy developers. (n.d.). Architecture overview, “Data flow.” Scrapy 2.13 documentation. 请求、下载器和记录的流向 ↩ ↩2 ↩3
-
Apify. (n.d.). CheerioCrawler guide, “How the crawler works.” Crawlee documentation. HTTP 与浏览器抓取 ↩ ↩2
-
CaiBorui. (2025). 网页采集原型 [本地导出与代码]。根目录
results.json及其两个同内容副本按一份计,另查results2.json、Node 目录的逐行 JSON 和主库crawler.sqlite。按完整 URL 比较;正文去除首尾空白,排除空值和字面占位符No content found。 ↩ ↩2 -
Scrapy developers. (n.d.). Jobs: pausing and resuming crawls, “Job directory.” Scrapy 2.13 documentation. 持久化队列与独立作业目录 ↩ ↩2 ↩3
-
Apify. (n.d.). RequestQueue. Crawlee 3.13 API reference. 请求的唯一标识与队列 ↩ ↩2
-
Scrapy developers. (n.d.). AutoThrottle extension, “How it works.” Scrapy 2.13 documentation. 按下载延迟节流 ↩ ↩2
-
Nottingham, M., & Fielding, R. (2012, April). Additional HTTP status codes, § 4 (RFC 6585). IETF. 429 与 Retry-After ↩
-
Scrapy developers. (n.d.). Downloader middleware, “HttpProxyMiddleware.” Scrapy 2.13 documentation. 按请求配置下载代理 ↩
-
Scrapy developers. (n.d.). Selecting dynamically-loaded content, introductory paragraph 2. Scrapy 2.13 documentation. 定位浏览器中的数据来源 ↩
-
Microsoft. (n.d.). Pages, “Multiple pages.” Playwright documentation. 同一上下文中的多个标签页 ↩ ↩2
-
CaiBorui. (2026). 活动标题与日程表的离线对照 [复核实验]。复用本机 Scrapy 2.13.2、html2text 2025.4.15、Cheerio 1.0.0-rc.12 和 Turndown 7.2.0。输入为文中合成样例,转换选项与两份原型一致。 ↩
-
Christie, D., & Mixmark contributors. (n.d.). Turndown, “Extending with plugins.” GitHub. GitHub Flavored Markdown 表格插件 ↩
-
Scrapy developers. (n.d.). Feed exports, “Serialization formats.” Scrapy 2.13 documentation. JSON 与 JSON Lines ↩
-
SQLite developers. (n.d.). Transaction, § 2.1, “Read transactions versus write transactions.” SQLite documentation. 单个写事务的限制 ↩
-
Requests. (n.d.). Quickstart, “Make a Request.” Requests documentation. 下载 HTTP 响应 ↩
-
Richardson, L. (n.d.). Beautiful Soup documentation, “CSS selectors.” Crummy. 按选择器提取 HTML 元素 ↩
-
Encode. (n.d.). Async support, “Opening and closing clients.” HTTPX documentation. 异步客户端与连接池复用 ↩
-
Puppeteer contributors. (n.d.). Puppeteer. Puppeteer 官方文档. Selenium Project. (n.d.). WebDriver. Selenium 官方文档 ↩
-
Colly Team. (n.d.). Getting started, “Callbacks.” Colly documentation. 处理响应的回调 ↩
-
ScrapeGraphAI. (n.d.). Scrapegraph-ai [Software]. GitHub. 模型提取项目. Firecrawl. (n.d.). Crawl. Firecrawl documentation. 托管采集接口 ↩