HTTP Operations
Making requests
Use context methods for HTTP operations, as they handle common tasks such as caching, using request sessions with sensible retry defaults, and checking the response status.
text = context.fetch_text(context.data_url, method="POST", headers=headers, data=body, cache_days=cache_days)
Handling bot blocking
Many sites employ bot blocking strategies. We believe this is primarily to mitigate Denial of Service attacks and manage server load, rather than protecting the content from extraction, since the purpose of the sites we scrape is dissemination of their block lists. As long as we are sensitive to our impact on their service and identifiable in their requests, we believe it is ok to work around their bot blocking strategies.
Blocking might result in error statuses like 403; redirects to error pages; or 200 status responses but with different content from what you've seen in the browser.
Header-based restrictions
If a request using zavod fails but your browser succeeds, try setting a more browser-like user-agent header.
http:
user_agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36 (zavod; opensanctions.org)
If that doesn't work, try more of the common headers sent by browsers:
HEADERS = {
"origin": "https://www.interpol.int",
"referer": "https://www.interpol.int/",
"sec-fetch-mode": "navigate",
"sec-fetch-site": "none",
"sec-fetch-user": "?1",
"upgrade-insecure-requests": "1",
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 (zavod; opensanctions.org)",
}
context.fetch_...(url, headers=HEADERS)
Network/geo-blocking
If it fails in production but not locally, the site might be blocking the production network IP range. It's common to block hosting provider networks for websites intended for humans only. It's also common to block requests from a country other than the publisher; if it works using a VPN exit point in that country, pass that country to the geolocation argument.
In both cases, route the request through the Zyte API (zavod.extract.zyte_api), which proxies and unblocks requests. The fetch_* helpers default to the httpResponseBody scrape type, which is faster and cheaper than browserHtml. Prefer it unless the page needs JavaScript (see below).
JavaScript challenges
If it works in the browser but you see different content when fetching using zavod or curl, there might be a javascript challenge that checks whether a full browser is rendering the page. This usually sets a cookie so the browser doesn't have to complete the challenge on each request. These challenges can also be intermittent.
Use zyte_api.fetch_html, whose html_source defaults to "browserHtml": it renders the page in a browser, executes the JavaScript, and returns the resulting DOM as parsed HTML. It requires an unblock_validator XPath that matches only when unblocking succeeded, so challenge pages aren't cached. If you need to wait for specific content or click to reveal data, use the actions argument.
The Zyte API
The helpers in zavod.extract.zyte_api route requests through the Zyte API, which handles proxying, geolocation, and browser rendering. They require the OPENSANCTIONS_ZYTE_API_KEY environment variable, so crawlers that use them set ci_test: false. Most take an optional geolocation (e.g. "US") and cache_days. For requests that need a POST body, custom headers, cookies, or browser actions, build a ZyteAPIRequest and call the lower-level fetch.
zavod.extract.zyte_api.fetch_text(context, url, geolocation=None, cache_days=None, expected_media_type=None, expected_charset=None)
Fetch a text document using the Zyte API.
The content type and charset can be used to assert expected types (and successful unblocking by Zyte) and for appropriate text decoding when the encoding can vary. Do so via the expected_ arguments unless more logic is required.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
Context
|
The context object. |
required |
url
|
str
|
The URL of the text document. |
required |
headers
|
A list of dicts of headers to send with the request. |
required | |
expected_media_type
|
Optional[str]
|
If set, assert that the media type in the response content-type header matches this value. |
None
|
expected_charset
|
Optional[str]
|
If set, assert that the charset in the response content-type header matches this value. |
None
|
Returns:
| Type | Description |
|---|---|
Tuple[bool, str | None, str | None, str]
|
A tuple of: - A boolean indicating whether the text was cached. - The media type of the response, None if cached. - The charset of the response, None if cached. - The text content. |
Source code in zavod/extract/zyte_api.py
zavod.extract.zyte_api.fetch_json(context, url, cache_days=None, expected_media_type='application/json', geolocation=None)
Returns:
| Type | Description |
|---|---|
Any
|
A JSON document. |
Source code in zavod/extract/zyte_api.py
zavod.extract.zyte_api.fetch_resource(context, filename, url, expected_media_type=None, expected_charset=None, geolocation=None, method=None, body=None, headers=None)
Fetch a resource using Zyte API and save to filesystem.
The content type and charset can be used to assert expected types (and successful unblocking by Zyte) and for appropriate text decoding when the encoding can vary. Do so via the expected_ arguments unless more logic is required.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
Context
|
The context object. |
required |
filename
|
str
|
The name to use when saving the file. |
required |
url
|
str
|
The URL of the resource. |
required |
expected_media_type
|
Optional[str]
|
If set, assert that the media type in the response content-type header matches this value. Not enforced when the file already exists locally. |
None
|
expected_charset
|
Optional[str]
|
If set, assert that the charset in the response content-type header matches this value. Not enforced when the file already exists locally. |
None
|
Returns:
| Type | Description |
|---|---|
Tuple[bool, str | None, str | None, Path]
|
A tuple of: - A boolean indicating whether the file was cached. - The media type of the response, None if cached. - The charset of the response, None if cached. - The path to the saved file. |
Source code in zavod/extract/zyte_api.py
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 | |
zavod.extract.zyte_api.fetch_html(context, url, unblock_validator, actions=[], html_source='browserHtml', javascript=None, geolocation=None, cache_days=None, retries=3, backoff_factor=3, previous_retries=0, absolute_links=False)
Fetch a web page using the Zyte API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
unblock_validator
|
str
|
XPath matching at least one element if and only if unblocking was successful. This is important to ensure we don't cache pages that weren't actually unblocked successfully. |
required |
html_source
|
str
|
browserHtml | httpResponseBody |
'browserHtml'
|
retries
|
int
|
The number of times to retry if unblocking fails. |
3
|
backoff_factor
|
int
|
Factor to scale the pause between retries. |
3
|
absolute_links
|
bool
|
Whether to convert relative links to absolute links. Doesn't take redirects into account. |
False
|
Returns:
| Type | Description |
|---|---|
_Element
|
The parsed HTML document serialized from the DOM. |
Source code in zavod/extract/zyte_api.py
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 | |
zavod.extract.zyte_api.fetch(context, zyte_request, cache_days=None)
Fetch using the Zyte API.
Note that this function uses the cache, but does not set the cache. This should be done by callers after verifying that the content is valid and worthy of being cached.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
Context
|
The context object. |
required |
zyte_request
|
ZyteAPIRequest
|
The request to send |
required |
cache_days
|
Optional[int]
|
The allowed age of a cache hit. |
None
|
Returns: A ZyteResult
Source code in zavod/extract/zyte_api.py
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 | |
zavod.extract.zyte_api.ZyteAPIRequest
dataclass
Container dataclass for possible arguments to the Zyte API.