Skip to content

Commit e3570af

Browse files
shixishclaude
andcommitted
feat(crawl): named create options and multi-value custom_headers
url_crawl_regex, url_process_regex, page_process_pattern, max_to_crawl_per_subdomain, max_to_process_per_subdomain, use_canonical, notify_webhook, notify_email on crawl() (query params on the existing GET). custom_headers accepts a str or a sequence, sent as repeated params. Recurring-crawl admin stays out. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent 4c7d899 commit e3570af

2 files changed

Lines changed: 144 additions & 6 deletions

File tree

‎src/diffbot/crawl.py‎

Lines changed: 52 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from dataclasses import dataclass
99
from datetime import datetime
1010
from enum import Enum
11-
from typing import TYPE_CHECKING, Any, AsyncIterator, Dict, Iterator, List, Optional
11+
from typing import TYPE_CHECKING, Any, AsyncIterator, Dict, Iterator, List, Optional, Sequence, Union
1212

1313
from .errors import APIError, JobError
1414
from .types import CrawlDownloadFormat, CrawlJob
@@ -44,9 +44,18 @@ def crawl(
4444
url_process_pattern: Optional[str] = None,
4545
obey_robots: bool = False,
4646
use_proxies: bool = False,
47-
custom_headers: Optional[str] = None,
47+
custom_headers: Optional[Union[str, Sequence[str]]] = None,
4848
watch: bool = False,
4949
poll_interval: float = 2.0,
50+
*,
51+
url_crawl_regex: Optional[str] = None,
52+
url_process_regex: Optional[str] = None,
53+
page_process_pattern: Optional[str] = None,
54+
max_to_crawl_per_subdomain: Optional[int] = None,
55+
max_to_process_per_subdomain: Optional[int] = None,
56+
use_canonical: Optional[bool] = None,
57+
notify_webhook: Optional[str] = None,
58+
notify_email: Optional[str] = None,
5059
) -> Iterator[CrawlEvent]:
5160
"""Create a crawler job and yield a JOB_CREATED event. If watch=True, poll until
5261
completion and yield URL_PROCESSED events for each crawled URL.
@@ -56,7 +65,11 @@ def crawl(
5665
5766
Recommended pattern for tools that can't block on a long crawl: start with
5867
``crawl(..., watch=False)``, poll :func:`crawl_get_job` until its
59-
``jobStatus.status`` is terminal, then fetch results with :func:`crawl_download`."""
68+
``jobStatus.status`` is terminal, then fetch results with :func:`crawl_download`.
69+
70+
Create options are sent as query params on the existing GET. ``custom_headers`` is
71+
one ``"Name: value"`` string or a sequence of them (sent as repeated params).
72+
Recurring-crawl admin (``repeat``, ``maxRounds``, ...) is not exposed."""
6073
if not site.startswith("http"):
6174
site = f"https://{site}"
6275
if not job_name:
@@ -66,6 +79,16 @@ def crawl(
6679
client, job_name, site, max_to_crawl, max_to_process, hops, restrict_domain,
6780
api_url, crawl_delay, url_crawl_pattern, url_process_pattern,
6881
obey_robots, use_proxies, custom_headers,
82+
{
83+
"urlCrawlRegEx": url_crawl_regex,
84+
"urlProcessRegEx": url_process_regex,
85+
"pageProcessPattern": page_process_pattern,
86+
"maxToCrawlPerSubdomain": max_to_crawl_per_subdomain,
87+
"maxToProcessPerSubdomain": max_to_process_per_subdomain,
88+
"useCanonical": None if use_canonical is None else int(use_canonical),
89+
"notifyWebhook": notify_webhook,
90+
"notifyEmail": notify_email,
91+
},
6992
)
7093
_raise_on_create_error(client.request("GET", client.crawler_url, params=params))
7194

@@ -123,7 +146,8 @@ def _build_crawl_params(client: Any, job_name: str, site: str, max_to_crawl: int
123146
max_to_process: int, hops: int, restrict_domain: bool,
124147
api_url: str, crawl_delay: float, url_crawl_pattern: Optional[str],
125148
url_process_pattern: Optional[str], obey_robots: bool,
126-
use_proxies: bool, custom_headers: Optional[str]) -> Dict[str, Any]:
149+
use_proxies: bool, custom_headers: Optional[Union[str, Sequence[str]]],
150+
named: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
127151
params: Dict[str, Any] = {
128152
"token": client.token,
129153
"name": job_name,
@@ -146,7 +170,10 @@ def _build_crawl_params(client: Any, job_name: str, site: str, max_to_crawl: int
146170
if use_proxies:
147171
params["useProxies"] = 1
148172
if custom_headers:
149-
params["customHeaders"] = custom_headers
173+
# a sequence becomes repeated ``customHeaders=`` params; a lone string stays a plain value
174+
params["customHeaders"] = custom_headers if isinstance(custom_headers, str) else list(custom_headers)
175+
if named:
176+
params.update({k: v for k, v in named.items() if v is not None})
150177
return params
151178

152179

@@ -179,9 +206,18 @@ async def crawl_async(
179206
url_process_pattern: Optional[str] = None,
180207
obey_robots: bool = False,
181208
use_proxies: bool = False,
182-
custom_headers: Optional[str] = None,
209+
custom_headers: Optional[Union[str, Sequence[str]]] = None,
183210
watch: bool = False,
184211
poll_interval: float = 2.0,
212+
*,
213+
url_crawl_regex: Optional[str] = None,
214+
url_process_regex: Optional[str] = None,
215+
page_process_pattern: Optional[str] = None,
216+
max_to_crawl_per_subdomain: Optional[int] = None,
217+
max_to_process_per_subdomain: Optional[int] = None,
218+
use_canonical: Optional[bool] = None,
219+
notify_webhook: Optional[str] = None,
220+
notify_email: Optional[str] = None,
185221
) -> AsyncIterator[CrawlEvent]:
186222
if not site.startswith("http"):
187223
site = f"https://{site}"
@@ -192,6 +228,16 @@ async def crawl_async(
192228
client, job_name, site, max_to_crawl, max_to_process, hops, restrict_domain,
193229
api_url, crawl_delay, url_crawl_pattern, url_process_pattern,
194230
obey_robots, use_proxies, custom_headers,
231+
{
232+
"urlCrawlRegEx": url_crawl_regex,
233+
"urlProcessRegEx": url_process_regex,
234+
"pageProcessPattern": page_process_pattern,
235+
"maxToCrawlPerSubdomain": max_to_crawl_per_subdomain,
236+
"maxToProcessPerSubdomain": max_to_process_per_subdomain,
237+
"useCanonical": None if use_canonical is None else int(use_canonical),
238+
"notifyWebhook": notify_webhook,
239+
"notifyEmail": notify_email,
240+
},
195241
)
196242
_raise_on_create_error(await client.request("GET", client.crawler_url, params=params))
197243

‎tests/test_crawl.py‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,3 +275,95 @@ def handler(request: httpx.Request) -> httpx.Response:
275275
with pytest.raises(APIError, match="name is over 30 chars"):
276276
async for _ in db.crawl("https://example.com", job_name="x" * 31):
277277
pass
278+
279+
"""
280+
Named create options and multi-value custom_headers (S2)
281+
"""
282+
283+
284+
def _capture_create():
285+
seen = []
286+
287+
def handler(request: httpx.Request) -> httpx.Response:
288+
seen.append(request)
289+
return httpx.Response(200, json={"jobs": [{"name": "j"}]})
290+
291+
return seen, handler
292+
293+
294+
NAMED = dict(
295+
url_crawl_regex="^https://a/", url_process_regex="/p/", page_process_pattern="<article",
296+
max_to_crawl_per_subdomain=5, max_to_process_per_subdomain=3, use_canonical=False,
297+
notify_webhook="https://hook", notify_email="a@b.example",
298+
)
299+
300+
301+
def test_crawl_named_options_are_query_params_on_get():
302+
seen, handler = _capture_create()
303+
db = make_client(handler)
304+
next(db.crawl("https://example.com", job_name="j", **NAMED))
305+
(req,) = seen
306+
assert req.method == "GET"
307+
p = req.url.params
308+
assert p["urlCrawlRegEx"] == "^https://a/"
309+
assert p["urlProcessRegEx"] == "/p/"
310+
assert p["pageProcessPattern"] == "<article"
311+
assert p["maxToCrawlPerSubdomain"] == "5"
312+
assert p["maxToProcessPerSubdomain"] == "3"
313+
assert p["useCanonical"] == "0"
314+
assert p["notifyWebhook"] == "https://hook"
315+
assert p["notifyEmail"] == "a@b.example"
316+
317+
318+
def test_crawl_named_options_absent_by_default():
319+
seen, handler = _capture_create()
320+
db = make_client(handler)
321+
next(db.crawl("https://example.com", job_name="j"))
322+
keys = set(seen[0].url.params.keys())
323+
assert keys.isdisjoint({
324+
"urlCrawlRegEx", "urlProcessRegEx", "pageProcessPattern", "maxToCrawlPerSubdomain",
325+
"maxToProcessPerSubdomain", "useCanonical", "notifyWebhook", "notifyEmail", "customHeaders",
326+
})
327+
328+
329+
def test_crawl_use_canonical_true_sends_1():
330+
seen, handler = _capture_create()
331+
db = make_client(handler)
332+
next(db.crawl("https://example.com", job_name="j", use_canonical=True))
333+
assert seen[0].url.params["useCanonical"] == "1"
334+
335+
336+
def test_crawl_custom_headers_single_and_multi():
337+
seen, handler = _capture_create()
338+
db = make_client(handler)
339+
next(db.crawl("https://example.com", job_name="j", custom_headers="X-A: 1"))
340+
assert seen[0].url.params.get_list("customHeaders") == ["X-A: 1"]
341+
seen.clear()
342+
next(db.crawl("https://example.com", job_name="j", custom_headers=["X-A: 1", "X-B: 2"]))
343+
assert seen[0].url.params.get_list("customHeaders") == ["X-A: 1", "X-B: 2"]
344+
seen.clear()
345+
next(db.crawl("https://example.com", job_name="j", custom_headers=[]))
346+
assert "customHeaders" not in seen[0].url.params
347+
348+
349+
@pytest.mark.anyio
350+
async def test_async_crawl_named_options_and_multi_headers():
351+
seen, handler = _capture_create()
352+
db = DiffbotAsync(token="test-token", transport=httpx.MockTransport(handler))
353+
async for _ in db.crawl("https://example.com", job_name="j", custom_headers=("X-A: 1", "X-B: 2"), **NAMED):
354+
break
355+
p = seen[0].url.params
356+
assert p.get_list("customHeaders") == ["X-A: 1", "X-B: 2"]
357+
assert p["urlCrawlRegEx"] == "^https://a/"
358+
assert p["useCanonical"] == "0"
359+
assert p["maxToProcessPerSubdomain"] == "3"
360+
assert p["notifyEmail"] == "a@b.example"
361+
362+
363+
@pytest.mark.anyio
364+
async def test_async_crawl_custom_headers_single_string():
365+
seen, handler = _capture_create()
366+
db = DiffbotAsync(token="test-token", transport=httpx.MockTransport(handler))
367+
async for _ in db.crawl("https://example.com", job_name="j", custom_headers="X-A: 1"):
368+
break
369+
assert seen[0].url.params.get_list("customHeaders") == ["X-A: 1"]

0 commit comments

Comments
 (0)