API Conventions
For lifecycle stages and the warning-to-removal process, see the project’s deprecation policy.
Standard Parameter Names
All scrapers in juscraper follow a unified API convention for parameter names.
Search
| Parameter | Description |
|---|---|
pesquisa |
The search query string (canonical name) |
buscar_em |
Where to look for pesquisa, when the portal lets you choose |
Deprecated aliases: query, termo — accepted with DeprecationWarning, will be removed in v1.0.
buscar_em takes "ementa" (only the headnote) or "inteiro_teor" (the full text of the decision, which includes the headnote). A value only one portal offers stays in that tribunal alone. Each scraper accepts only the values its portal has, and its default is the field the portal searches by default, so pesquisa alone keeps working as before. Use it to search terms in decisions without an ementa, such as single-judge decisions and sentenças:
tjrn.cjsg("dano moral", buscar_em="inteiro_teor", decisoes="Sentença")Every scraper that lets you pick the field uses buscar_em: STM, TJSC, TJPA, TJRN and TJDFT cjsg, and STF listar_decisoes/contar_decisoes. STM also takes "numero" (the case number), which only its portal offers. In STF and TJDFT, "inteiro_teor" adds the full text to the fields of the default search, as the portal option does, and that default search already goes beyond the headnote (in STF, the decision text, indexing and parties; in TJDFT, the espelho of the acórdão). TJPA sends the choice to its API, which ignored it on 26 Nov 2026, as did the portal’s own website: both values searched the headnote and the full text. The older names (STM and TJSC campo, TJPA query_scope, STF and TJDFT inteiro_teor) are deprecated aliases; see the Migration Guide. In the eSAJ family, TJSP and TRF3, pesquisa already searches the whole document and ementa is a separate text filter that combines with it.
Date Filters
| Parameter | Description |
|---|---|
data_julgamento_inicio |
Start date for judgment filtering |
data_julgamento_fim |
End date for judgment filtering |
data_publicacao_inicio |
Start date for publication filtering |
data_publicacao_fim |
End date for publication filtering |
Generic aliases: data_inicio / data_fim map to data_julgamento_inicio / data_julgamento_fim. Cannot be used together with the specific names — raises ValueError. They do not apply to DataJud listar_processos, which filters by filing date: use data_ajuizamento_inicio / data_ajuizamento_fim.
The date filters above (and the other data_*_inicio/data_*_fim date filters) are inclusive and cover whole days: data_julgamento_fim="2024-03-15" includes everything dated March 15. Where a scraper builds the time of a boundary itself (TJMT, STM, TJBA, STF, DataJud), the backend’s precision and time zone were measured live and recorded next to the code. STM splits days in UTC, as its own search form does. PDPJ’s data_atualizacao_* and data_primeiro_ajuizamento_* are timestamps (yyyy-MM-dd'T'HH:mm:ss.SSS) sent as given, so a whole day needs the end time spelled out.
Deprecated aliases: data_julgamento_de / data_julgamento_ate, data_publicacao_de / data_publicacao_ate — accepted with DeprecationWarning.
Accepted input formats
Endpoints using the shared date-coercion pipeline accept the following formats for supported date filters. See CONTRIBUTING.md > Schemas pydantic > Pipeline canônico (wiring) for the implementation:
"DD/MM/AAAA"— Brazilian short form (e.g."01/03/2024")"DD-MM-AAAA"— Brazilian with dashes (e.g."01-03-2024")"AAAA-MM-DD"— ISO-8601 short form (e.g."2024-03-01")"AAAA/MM/DD"— ISO-8601 with slashes (e.g."2024/03/01")datetime.datedatetime.datetime(the time component is dropped)
The pipeline coerces every recognized input to whatever format the tribunal’s backend expects — eSAJ uses DD/MM/AAAA, REST/JSON backends like TJDFT use AAAA-MM-DD. The exact backend format is declared per schema via the BACKEND_DATE_FORMAT: ClassVar[str] attribute, so callers don’t need to know it. An empty string and None pass through unchanged (open-ended search). An unrecognized format surfaces as a single ValueError("...Formato esperado: ...") raised by validate_intervalo_datas.
Pagination
| Parameter | Type | Description |
|---|---|---|
paginas |
int \| list \| range \| None |
Pages to download (1-based) |
None(default): downloads all available pagesint: shorthand —paginas=3is equivalent torange(1, 4)range: e.g.,range(1, 4)downloads pages 1, 2, 3list: e.g.,[1, 3, 5]downloads specific pages
A page listed twice is downloaded once, in the position where it first appears. When the portal reports the total, pages beyond it are not requested and are reported in a single warning on the scraper’s logger (juscraper.<sigla>, such as juscraper.tjsp or juscraper.falcao). Exceptions: TJAP, which does not report the total, still requests an explicit page beyond the end from the portal; PDPJ and DataJud walk their cursor (it only moves forward) up to the largest requested page, return only the requested pages and stop silently at the end of the results.
Portals that serve only the first results of a search (10,000 in TJBA, TJMT, TJPB, TJRO and Falcão) raise ValueError before any request when a requested page is beyond that cap. With paginas=None, the download stops at the cap with a UserWarning, except where auto_chunk splits the search by date (TJBA, TJMT, TJPB, TJRO, ComunicaCNJ and Falcão, see “Result caps” below). ComunicaCNJ and Falcão also stop their count at 10,000, so a count of 10,000 does not tell the real total. When the count reaches it and the search is not split, both emit the same UserWarning, suggesting a split by date: with paginas=None and, in ComunicaCNJ, with a requested page past the last page of those 10,000 results. listar_comunicacoes downloads only the pages within them; when no requested page is within them, it requests page 1 just to read the count, because the API answers HTTP 500 to a direct jump past the cap.
When a page fails (after the retries) and another requested page was already downloaded, the search stops and raises juscraper.core.exceptions.ColetaParcialError: .resultado holds the pages downloaded so far, already parsed, in the format of the full return (a DataFrame, also in *_download), __cause__ is the page’s exception, and the message lists the missing pages as a value for paginas= (PDPJ pesquisa, which follows a cursor and does not know the total, gives the first missing page). A failure on the first requested page is raised as is. This holds for every paginated cjsg and cjpg, ComunicaCNJ listar_comunicacoes and PDPJ pesquisa; the eSAJ, Falcão, STF, DataJud and TJAP keep their own loops (see Per-row failures).
Page Size
| Parameter | Type | Description |
|---|---|---|
tamanho_pagina |
int |
Results per page (default 10; TJES uses 20 because of the Elasticsearch backend) |
tamanho_pagina is the canonical name across all tribunals that expose page-size control. Each tribunal accepts exactly one deprecated alias — the historical name from its specific backend — emitting DeprecationWarning:
| Tribunal | Deprecated alias |
|---|---|
| TJBA | items_per_page |
| TJDFT | quantidade_por_pagina |
TJES (cjsg and cjpg) |
per_page |
| TJGO | qtde_itens_pagina |
| TJMG | linhas_por_pagina |
| TJMT | quantidade_por_pagina |
Passing both the canonical name and the alias in the same call raises ValueError. Cross-tribunal aliases (e.g. passing linhas_por_pagina to the TJBA scraper) are rejected with TypeError via extra="forbid". So is a date alias whose canonical filter the court lacks (e.g. data_inicio, which maps to data_julgamento_inicio, in TJGO): the alias emits its DeprecationWarning, then the schema raises TypeError.
Parameter Support by Tribunal
| Parameter | TJSP (cjsg/cjpg) | TJDFT | TJPR | TJRS |
|---|---|---|---|---|
pesquisa |
Yes | Yes | Yes | Yes |
data_julgamento_inicio/fim |
Yes | Yes | Yes | Yes |
data_publicacao_inicio/fim |
No | Yes | Yes | Yes |
paginas (all types) |
Yes | Yes | Yes | Yes |
paginas=None (all pages) |
Yes | Yes | Yes | Yes |
Migration Guide
From query / termo to pesquisa
# Before
scraper.cjsg(query="direito civil")
scraper.cjsg_download(termo="direito civil")
# After
scraper.cjsg(pesquisa="direito civil")
scraper.cjsg_download(pesquisa="direito civil")From _de/_ate to _inicio/_fim
# Before
scraper.cjsg(query="teste", data_julgamento_de="01/01/2023", data_julgamento_ate="31/12/2023")
# After
scraper.cjsg(pesquisa="teste", data_julgamento_inicio="01/01/2023", data_julgamento_fim="31/12/2023")From data_inicio/fim to data_julgamento_inicio/fim (TJSP)
# Before
scraper.cjsg("teste", data_inicio="01/01/2023", data_fim="31/12/2023")
# After (canonical)
scraper.cjsg("teste", data_julgamento_inicio="01/01/2023", data_julgamento_fim="31/12/2023")
# Or (generic alias still works with DeprecationWarning)
scraper.cjsg("teste", data_inicio="01/01/2023", data_fim="31/12/2023")Pagination default change
# Before: default was paginas=1 (only first page)
scraper.cjsg(pesquisa="teste") # downloaded 1 page
scraper.cjsg(pesquisa="teste", paginas=3) # downloaded pages 1-3
# After: default is paginas=None (all pages)
scraper.cjsg(pesquisa="teste") # downloads ALL pages
scraper.cjsg(pesquisa="teste", paginas=1) # downloads page 1 only
scraper.cjsg(pesquisa="teste", paginas=3) # downloads pages 1-3TRF3 cpopg_parse: from htmls to brutos
The TRF3 public portal stopped serving the JSF detail page, so cpopg_download now returns one dict of JSON API envelopes per CNJ instead of HTML. cpopg_parse takes those dicts as brutos; htmls= still works with a DeprecationWarning, but HTML saved from the old portal raises TypeError and must be downloaded again.
# Before
htmls = trf3.cpopg_download(cnjs)
df = trf3.cpopg_parse(htmls=htmls, id_cnj_list=cnjs)
# After
brutos = trf3.cpopg_download(cnjs)
df = trf3.cpopg_parse(brutos, cnjs)From campo, query_scope and inteiro_teor to buscar_em
STM, TJSC, TJPA, STF and TJDFT used their own names and values to pick where to look for pesquisa. They now take buscar_em, with "ementa" or "inteiro_teor". The old names still work with a DeprecationWarning, which names the new value, and will be removed in 0.7.0. Passing an old name together with buscar_em raises ValueError. Where the old name was an explicit parameter (TJSC, TJPA and TJDFT cjsg_download), an old value given to buscar_em, which is where the old parameter lands when passed by position (tjsc.cjsg("dano moral", 1, "I")), is converted with a warning too.
| Tribunal | Before | After |
|---|---|---|
| STM | campo="ementa" / "inteiro_teor" / "numero" |
buscar_em= with the same value |
| TJSC | campo="E" / campo="I" |
buscar_em="ementa" / buscar_em="inteiro_teor" |
| TJPA | query_scope="ementa" / "inteiroTeor" / "inteiroteor" |
buscar_em="ementa" / "inteiro_teor" / "inteiro_teor" |
| STF, TJDFT | inteiro_teor=False / inteiro_teor=True |
buscar_em="ementa" / buscar_em="inteiro_teor" |
# Before
tjsc.cjsg("dano moral", campo="I")
stf.listar_decisoes("pejotização", inteiro_teor=True, paginas=1)
# After
tjsc.cjsg("dano moral", buscar_em="inteiro_teor")
stf.listar_decisoes("pejotização", buscar_em="inteiro_teor", paginas=1)TJAP cjsg: from votacao="Unanime" to votacao="Unânime"
The Tucujuris portal only recognizes "Unânime", with the accent. On 15 Nov 2026, votacao="Unanime", the spelling the docstring suggested up to 0.5.0, returned the same decisions as "Maioria". It is now sent as "Unânime" with a DeprecationWarning, and will be removed in 0.7.0.
# Before
tjap.cjsg("dano", votacao="Unanime")
# After
tjap.cjsg("dano", votacao="Unânime")Boolean filters are keyword-only
Boolean parameters of cjsg/cjsg_download in TJAP, TJBA, TJDFT, TJES, TJMT, TJPB, TJRJ, TJRO and TJTO (also cjpg/cjpg_download in TJTO), of cpopg in TJPE, TRF1 and TRF5, and the parameters after them in the signature, are now keyword-only. Passing them by position still works with a DeprecationWarning, and will raise TypeError from 0.7.0.
# Before
trf1.cpopg("0000000-00.0000.4.01.0000", True)
# After
trf1.cpopg("0000000-00.0000.4.01.0000", download_pecas=True)TJGO cjsg: id_instancia takes the Projudi form values
The “Instância” dropdown of the Projudi search form offers 0 (all), 15 (Tribunal) and 151 (Turma de Uniformização / Turmas Recursais). The docstring suggested 1, 2 and 3, which the form never offered. 2 and 3 are now sent as 151 and 15 with a DeprecationWarning, and will be removed in 0.7.0. 1 (first degree) has no replacement, because the current form has no first-degree option: it is still sent as is, with a DeprecationWarning, until 0.7.0.
# Before
tjgo.cjsg("dano moral", id_instancia=3)
# After
tjgo.cjsg("dano moral", id_instancia=15)eSAJ cjsg, eSAJ cjpg and TRF6 cpopg: from relatora/magistrado to relator
The parsers used to turn the portal label into the column name. The eSAJ portals (TJAC, TJAL, TJAM, TJCE, TJMS and TJSP) label the rapporteur as “Relator(a):”, which became a relatora column in cjsg; the eSAJ first-instance search (cjpg, in TJSP and TJMS) labels the judge as “Magistrado:”, which became magistrado; the TRF6 cpopg (eproc) did the same for the judge on the case cover. All of them now deliver relator, the name used by the other courts, also for first-instance decisions. In TJSP, cjsg rows labelled “Relator:” already came out as relator, so a search with both labels split the rapporteur across two columns; it is now a single column. There is no deprecation cycle: a DataFrame cannot keep both names without duplicating the data.
# Before
df["relatora"] # eSAJ cjsg
df["magistrado"] # eSAJ cjpg, TRF6 cpopg
# After
df["relator"]
# DataFrames saved before the change
df = df.rename(columns={"relatora": "relator", "magistrado": "relator"})TJDFT cjsg: from the API column names to the canonical ones
The TJDFT parser used to pass the API records through untouched, so the DataFrame carried the API’s camelCase keys and lacked the columns every other court returns. Four of them now take the canonical names: nomeRelator becomes relator, descricaoOrgaoJulgador becomes orgao_julgador, dataJulgamento becomes data_julgamento and dataPublicacao becomes data_publicacao. The other API keys (decisao, codigoClasseCnj, turmaRecursal…) keep their names, since they have no canonical counterpart. There is no deprecation cycle: a DataFrame cannot keep both names without duplicating the data.
# Before
df[["nomeRelator", "descricaoOrgaoJulgador", "dataJulgamento", "dataPublicacao"]]
# After
df[["relator", "orgao_julgador", "data_julgamento", "data_publicacao"]]
# DataFrames saved before the change
df = df.rename(columns={
"nomeRelator": "relator",
"descricaoOrgaoJulgador": "orgao_julgador",
"dataJulgamento": "data_julgamento",
"dataPublicacao": "data_publicacao",
})TJSP cpopg/cposg: method="api" removed
The api.tjsp.jus.br lookup stopped returning processes (it answers [] even for processes that exist), so method="api" was removed without a deprecation cycle. Passing it raises ValueError before any request. Use method="html", the default; the HTML pages carry the same data and more.
# Before
tjsp.cpopg("1000149-71.2024.8.26.0346", method="api")
# After
tjsp.cpopg("1000149-71.2024.8.26.0346")cpopg_parse and cposg_parse no longer read the .json files the API download used to save.
TJSP cjpg/cpopg/cposg: failures stay in the result
A case or page that fails no longer drops out of the result with only a log line. In cpopg (table basicos) and cposg, every requested CNJ has a row, and the motivo_falha column is None for the cases read. A CNJ that was not downloaded keeps a row with only the number and the reason: nao_encontrado when the public lookup does not show it (no such case, or under seal), entrada_invalida, http_<status>, conexao, timeout or resposta_inesperada. Download and parse failures go into a single UserWarning, and cpopg_download/cposg_download return them as {cnj: motivo_falha}. The download also records them in falhas_download.json, inside its cpopg/ or cposg/ folder, so cpopg_parse/cposg_parse return the same failure rows as the one-step call. The parse step reads the whole cpopg/ or cposg/ folder; the one-step cpopg/cposg keeps only the requested CNJs, so cases and failures left in download_path by an earlier *_download stay out of its result.
res = tjsp.cpopg(cnjs)
falhas = res["basicos"].query("motivo_falha.notna()")A lost cjpg page has no row to carry the reason, so a partial read raises ColetaParcialError, as in the eSAJ auto-chunk; the DataFrame of the pages read is in .resultado. Each page from the second on gets up to five requests, and an HTTP error status counts as a failure; a page that fails all of them is lost the same way:
from juscraper.core.exceptions import ColetaParcialError
try:
df = tjsp.cjpg("dano moral")
except ColetaParcialError as erro:
df = erro.resultadoDate format flexibility
Wired endpoints accept multiple input formats and coerce to the backend’s expected representation. The four examples below all produce the same request:
import datetime as dt
import juscraper as jus
tjsp = jus.scraper("tjsp") # eSAJ backend (DD/MM/AAAA)
tjdft = jus.scraper("tjdft") # REST JSON backend (AAAA-MM-DD)
# String, any of the four supported formats — coerced internally:
tjsp.cjsg("dano moral", paginas=1, data_julgamento_inicio="01/03/2024")
tjsp.cjsg("dano moral", paginas=1, data_julgamento_inicio="2024-03-01")
tjdft.cjsg("habeas", paginas=1, data_julgamento_inicio="01/03/2024")
tjdft.cjsg("habeas", paginas=1, data_julgamento_inicio="2024-03-01")
# Or pass a date / datetime directly:
tjsp.cjsg("dano moral", paginas=1, data_julgamento_inicio=dt.date(2024, 3, 1))Auto-chunking (eSAJ family)
Several eSAJ endpoints (cjpg/cjsg in TJSP and TJMS, plus cjsg in TJAC, TJAL, TJAM, TJCE) cap each request at a one-year data_julgamento_* window. When the user asks for a longer interval, the scraper automatically splits the request into calendar-year windows, fetches each one, and concatenates the results — deduplicating by cd_acordao (cjsg) or id_processo (cjpg).
Each window ends the day before the same date one year later (01/01/2013–31/12/2013, then 01/01/2014–31/12/2014). The eSAJ backend only accepts data_julgamento_fim strictly before data_julgamento_inicio plus one calendar year and answers HTTP 404 otherwise, so a fixed day count would either drift or produce windows the server rejects.
import juscraper as jus
tjsp = jus.scraper("tjsp")
# Six-year span: scraper sends 6 requests under the hood and returns
# a single deduplicated DataFrame.
df = tjsp.cjsg(
pesquisa="dano moral",
data_julgamento_inicio="01/01/2018",
data_julgamento_fim="31/12/2024",
)The behaviour is controlled by auto_chunk: bool = True (default on). With auto_chunk=False, a data_julgamento_* interval the server would reject (end on or after the same date one year later) raises ValueError before any request. This helps input validation paths that want to fail before submitting a long job. data_publicacao_* is never split, so the same check applies to it in either mode:
tjsp.cjsg(
pesquisa="dano moral",
data_julgamento_inicio="01/01/2018",
data_julgamento_fim="31/12/2024",
auto_chunk=False, # raises ValueError ("aceita no máximo 1 ano(s)")
)If a window still fails after the HTTP retries (network errors, 4xx, 5xx), the scraper tries the remaining windows and then raises juscraper.core.exceptions.ColetaParcialError. A partial result never comes back as if it were complete. The error carries the work already done: .resultado holds the deduplicated DataFrame of the windows that succeeded, and .falhas lists (inicio, fim, exception) for the ones to retry:
from juscraper.core.exceptions import ColetaParcialError
try:
df = tjsp.cjsg("dano moral", data_julgamento_inicio="01/01/2018", data_julgamento_fim="31/12/2024")
except ColetaParcialError as erro:
df = erro.resultado
print(erro.falhas)The paginated cjsg and cjsg_download of the other courts (and TJES and TJTO cjpg), ComunicaCNJ listar_comunicacoes and PDPJ pesquisa raise it too when a result page fails with another page already downloaded (see Pagination). The search stops at that page: .resultado holds the pages read before it (as a DataFrame, also in cjsg_download), .falhas holds only that failure, and the message lists the missing pages, to request again with paginas=. In TJRS this includes a page answered with a Solr error in place of the results (TJRSBuscaError), and in TJTO a search blocked by the AWS WAF. A failure on the first page requested raises the original exception.
DataJud’s listar_processos follows the same rule. When a page fails (HTTP error, a 200 body that is not JSON, malformed response, a response with _shards.failed > 0, or a page that ends before the exact hits.total), the remaining aliases are still queried and ColetaParcialError is raised at the end. .resultado holds every record received, from all aliases, and each item in .falhas is (None, None, exception); the error message names the alias and the page that failed. A 200 body that is not JSON (a gateway or maintenance page) arrives as InvalidJSONResponseError, with the URL, the status and the start of the body; it is not retried.
Combining auto_chunk=True with paginas is rejected when the interval is long enough to actually trigger chunking: the multi-window semantics for paginas are ambiguous (each window? aggregated budget?) and the design prefers to fail explicitly. For short intervals where chunking is a no-op, paginas works as usual.
Result caps (TJBA, TJMT, TJPB, TJRO, ComunicaCNJ, Falcão)
The cjsg of TJBA, TJMT, TJPB and TJRO has a different limit: the portal reports the full total of a search but only serves its first 10,000 results. ComunicaCNJ listar_comunicacoes and Falcão listar_decisoes stop their count at 10,000, so a window whose count reaches 10,000 may hold more and is split as well. With paginas=None and auto_chunk=True (default), a search above that cap is split by date (publication date in TJBA and TJMT, judgment date in TJRO, availability date in ComunicaCNJ, filing date, data_juntada, in Falcão) and every window is downloaded. In TJPB the split follows the date the backend filters in data_julgamento_*, an internal release date rather than the dt_ementa of each row, so a window can return rows whose data_julgamento falls outside it; cjsg still applies its local filter on data_julgamento when the caller passes dates. The split follows the count the portal reports: a window above the cap is halved until each part fits, so no window size has to be guessed. A search that fits the cap is sent exactly as before.
tjro = jus.scraper("tjro")
df = tjro.cjsg("servidor público", data_julgamento_inicio="01/01/2024") # more than 10,000 resultsWhat to expect from a split search:
- Windows come from the most recent to the oldest. The portal order (relevance in TJRO) holds inside each window, not across them.
- The first split emits a
UserWarningwith the total and the approximate number of requests, so a long collection does not start unnoticed. - In ComunicaCNJ and Falcão the real total is unknown, so the first warning gives a minimum number of requests, and a broad term (one with 10,000 or more results per day) can take a very long collection. Pass
auto_chunk=Falseto keep the first 10,000 results. Falcão blocks the IP for hours after a burst of requests: narrow the search before splitting a broad term. - Without
ordenacao, Falcão requestsordenacao="menos_recente"for a collection of every page, split or not (except inprecedentes, which has no filing date and keeps the relevance order), because its relevance order changes between calls and the pages are requested one by one (measured on 29/11/2026: the same page ofmenos_recentecame back identical in consecutive calls, including documents filed on the same day). Page 1 of the search, which shows it reaches the cap, is the first page of the split and is not requested again. The split does not apply to theprecedentescollection, which has no filing date. - A search without dates is split from 01/01/1990 (TJMT, TJPB and TJRO), 01/02/1980 (TJBA), 01/01/2000 (ComunicaCNJ) or 01/01/1900 (Falcão, the same start it sends when only
data_juntada_fimis given) to today. Records without the filter date, or dated outside that range, fall in no window: when the windows add up to less than the total the portal first reported, aUserWarningat the end gives both numbers. In ComunicaCNJ and Falcão, whose count stops at 10,000, the windows almost always add up to more, and such records can be left out without that warning. In TJMT, older monocratic decisions come without a publication date (the API reports 0001-01-01) and are left out this way. - A single day above the cap cannot be split: its first 10,000 results are returned, with a
UserWarning. - A row the portal returns in two different windows is kept once (by document id in TJMT, TJPB and TJRO; by
hash, case number, publication date and court body in TJBA, wherehashalone repeats across distinct rows; by the whole document in Falcão). Repetitions inside one window are kept as the portal sends them. - The portal keeps indexing during a long collection, so the number of rows can exceed the total the first page reported.
- It is slow and held in memory: one request per second, 10 results per page in TJRO (10,000 results take about 17 minutes; “dano moral”, with more than 120,000, takes hours). In TJBA and TJMT,
tamanho_paginareduces the number of requests. Narrow the search by date when you do not need everything: a TJBA decision takes about 35 KB of memory with its full text (measured on 1,299 decisions), so a search with a million results does not fit in RAM. - If a request fails after the split, the collection stops and raises
ColetaParcialError..resultadoholds the DataFrame of what was downloaded (also incjsg_download), and the message gives the interval still missing, to resume withdata_*_inicioanddata_*_fim. In Falcão, the downloaded pages also stay on disk, as in any failed collection. - Falcão also splits with
checkpoint_dir. The first session stores inmanifest.jsonthe end of the windows (data_juntada_fim, or today), so a resume on another day rebuilds the same windows; documents filed after that end are left out. Each window keeps its pages underjanelas/, andresume=Truereads them from disk and requests only the missing ones, without repeating the split warning, which only the first session emits. Page 1 of the search is not requested again with the fixed end, even withoutdata_juntada_fim, except whendata_juntada_iniciois today or later, a one-day window that is not split. When the split ends, the pages, without the repetitions across windows, move to the checkpoint root. A split checkpoint resumes only withpaginas=Noneandauto_chunk=True, and a checkpoint that already holds pages of an unsplit collection (auto_chunk=False) is not split, so those pages are kept.
With auto_chunk=False, paginas=None downloads the pages up to the cap and emits a UserWarning. An explicit paginas never splits: page numbers refer to the single search, and a page beyond the cap raises ValueError.
Pre-scraping count (count_only)
Empirical legal research often benefits from a quick estimate of how many results a query will return before committing to a long collection job (~2 s/result in cjsg/cjpg with sleep_time=0.5, so 5 000 hits ≈ 3 h). The count_only: bool = False flag — accepted by cjsg in TJAC, TJAL, TJAM, TJCE, TJMS, TJSP and by cjpg in TJMS and TJSP — short-circuits the public method to a single network call per window, extracts the total result count from the first-page HTML, and returns an int instead of a pd.DataFrame:
import juscraper as jus
tjsp = jus.scraper("tjsp")
# One POST + one GET. Returns an int.
n = tjsp.cjpg(
pesquisa="dano moral",
data_julgamento_inicio="01/01/2024",
data_julgamento_fim="31/12/2024",
count_only=True,
)
print(f"Estimated wall-clock for full collection: {n * 2 / 3600:.1f}h")Interaction with auto_chunk: when the interval exceeds one year and auto_chunk=True (default), count_only iterates the disjoint windows produced by iter_date_windows and sums the per-window counts. The sum is raw — the de-duplication step that the normal path performs by cd_acordao / id_processo does not apply here, so the returned number can slightly overestimate len(cjsg(...)) when documents are republished across windows (same cd_acordao appearing in two windows). For most estimation use cases this is the desired behaviour: the count reflects what the backend will hand over, not the deduplicated final shape.
Other edge cases:
paginasis ignored whencount_only=True(the probe always inspects page 1). AUserWarningis emitted if both are passed.auto_chunk=Falseplus an interval longer than one year still raisesValueError— consistent with the strict path.- Captcha or layout-change failures on page 1 propagate as
ValueErrorwith the same message as the regular path. - Tribunals not yet wired reject
count_onlyviaextra="forbid"(TypeError).
The underlying helpers cjsg_n_results(html) and cjpg_n_results(html) are exposed from juscraper.courts._esaj.parse and juscraper.courts.tjsp.cjpg_parse for callers that already hold the raw HTML.
Full text of acórdãos (eSAJ)
cjsg returns the ementa and cd_acordao, not the full decision. Two routes download the PDF of the acórdão and return its path:
baixar_acordao(cd_acordao, cd_foro), in TJCE, TJMS and TJSP, takes the codes of thecjsgrow: one request per acórdão.baixar_acordao_por_processo(processo, data_julgamento), in TJAC and TJSP, follows the process movements. It is the only route in TJAC, where the direct one asks for a reCAPTCHA, and in TJSP it serves who has the process number and the judgment date but notcd_acordao.
Each has a batch version for a cjsg DataFrame (baixar_acordaos and baixar_acordaos_por_processo), which adds caminho_acordao and motivo_falha to the rows.
TJAL and TJAM have neither route yet: getArquivo.do returns a reCAPTCHA there even with casChecked=true, as in TJAC.
Straight from cd_acordao (TJCE, TJMS and TJSP)
In these courts the direct route of the cjsg works without login or captcha: baixar_acordao(cd_acordao, cd_foro) makes one request to cjsg/getArquivo.do and writes <diretorio>/acordaos/<cd_acordao>.pdf; baixar_acordaos(df) reads the cd_acordao and cd_foro columns:
import juscraper as jus
tjsp = jus.scraper("tjsp")
df = tjsp.cjsg("dano moral", paginas=1)
df = tjsp.baixar_acordaos(df)
df[["processo", "cd_acordao", "caminho_acordao", "motivo_falha"]]In TJSP, the route without parameters answers with a page that sends the browser to the login of eSAJ’s CAS and, when nobody is logged in, back to the same URL with casChecked=true, which serves the PDF anonymously. The method sends casChecked=true from the start.
cd_acordao already identifies one acórdão, so there is no choice by date. When the court answers with an HTML page instead of the PDF (“Arquivo não localizado” for an unknown code, or a captcha or login page), baixar_acordao raises DocumentoNaoPdfError, from juscraper.courts._esaj.pasta, and writes nothing; in baixar_acordaos the row gets nao_pdf. A code that is empty or not only digits raises EntradaInvalidaError (entrada_invalida) before any request.
Through the process movements (TJAC and TJSP)
baixar_acordao_por_processo(processo, data_julgamento) follows the process movements in the second-degree consultation, as the R package tjsp by José de Jesus Filho does in tjsp_baixar_acordaos_cposg: no login and no captcha. baixar_acordaos_por_processo(df) reads the processo and data_julgamento columns:
tjac = jus.scraper("tjac")
df = tjac.cjsg("dano moral", paginas=1)
df = tjac.baixar_acordaos_por_processo(df)
df[["processo", "data_julgamento", "caminho_acordao", "motivo_falha"]]- Which acórdão. A process may have more than one (the appeal and its embargos de declaração, often with their own
cdProcesso). The method takes the first document whose type is an acórdão and whose movement date is on or afterdata_julgamento. The movement comes on the judgment day or a few days later, and the next acórdão of the same process comes after it. When two incidents have an acórdão on the same day, the date cannot tell them apart: the method returns the one from the incident listed first by the search, and aloggingwarning names the other. - What is returned. The PDF as the court publishes it, at
<diretorio>/acordaos/<cnj>_<cdProcesso>_<cdDocumento>.pdf. Text extraction is left to the caller. Long PDFs (100 pages and more in criminal chambers of TJSP) are a single acórdão with long votes, not a wider range of the case file. - Errors.
ProcessoNaoEncontradoErrorwhen the public consultation does not show the process: eSAJ answers the same way for a number that does not exist and for a process under judicial secrecy.AcordaoNaoEncontradoErrorwhen no acórdão is accessible from that date; the message counts the documents that asked for the process password.RespostaNaoPdfErrorwhen the PDF endpoint answers with something else (nothing is written).RespostaInesperadaErrorwhen a page is not in the known format.EntradaInvalidaError, aValueError, whenprocessodoes not have 20 digits ordata_julgamentois empty (None,NaN,NaT), in an unknown format or impossible (31/02); no request is made. Inbaixar_acordaos_por_processothese become themotivo_falhavaluesnao_encontrado,sem_acordao,nao_pdf,resposta_inesperadaandentrada_invalida; a PDF that could not be written to disk becomeserro_de_gravacao. All exceptions are imported fromjuscraper.courts._esaj.acordao. - Password-protected documents. Documents that ask for the process password are skipped. If the acórdão of the requested date is one of them, the method returns the next acórdão of the process instead; a
loggingwarning then says how many protected documents were skipped before the returned one. - Anti-bot block. The first row that gets
bloqueio_anti_botends the batch, because the block holds for the whole session: the following rows get the same reason without a request, and the rows already downloaded stay in the result. The same holds forbaixar_acordaosand forbaixar_sentencas. Retry only the failed rows later or from another IP. - Pace.
sleep_timeis the minimum interval between two requests to the court, also inside a single row: one TJSP acórdão takes the search, one page per incident, the movement pages and the folder of each candidate document.
Case documents of the first instance (TJSP)
Two methods download public documents of the first instance as PDF, with no login and no captcha. Documents that ask for the process password are left out (see jtrecenti/juscraper#481).
Documents linked to movements. cpopg(..., download_pecas=True, diretorio=...) downloads, in the same session that lists the movements, the PDF of each public document linked to a movement:
import juscraper as jus
tjsp = jus.scraper("tjsp")
resultado = tjsp.cpopg("0000564-95.2025.8.26.0068", download_pecas=True, diretorio="pecas")
resultado["movimentacoes"][["data", "movimento", "cd_documento", "documento_publico", "caminho_documento"]]- Columns. Every
cpopgcall (with or withoutdownload_pecas) now fillscd_documentoanddocumento_publicoinmovimentacoes, read from the movement HTML with no extra request.caminho_documentohas the PDF path, orNonewithoutdownload_pecas, for password-protected documents and for documents whose download failed. - Where files go.
<diretorio>/cpopg/<cnj>/documentos/<cdDocumento>.pdf.cpopgdeletes its download folder at the end, sodiretoriois required withdownload_pecas=True, is only accepted with it, and cannot be insidedownload_path.cpopg_download(..., download_pecas=True)writes the PDFs next to the process HTML. - Cost. Two requests per public document (the folder page and the PDF), after the movement pages of the process: eSAJ only opens a document whose movement page the session has already loaded. The process page is not requested again.
- Failures. A document that fails (eSAJ refuses access, the answer is not a PDF, network error) does not stop the process: the HTML is saved, the PDF is missing, and a single
UserWarninglists the failures at the end. A latercpopg_download(..., download_pecas=True)on the same folder downloads the process again only when a public PDF is missing, and requests only the missing PDFs. download_pecas=Truerequiresbaixar_movimentacoes=True; otherwise it raisesValueErrorbefore any request.
Sentences from cjpg. Each cjpg row has the four codes of the “Visualizar Inteiro Teor” link: cd_processo, cd_foro, nm_alias (often empty) and cd_documento. baixar_sentenca(cd_processo, cd_foro, cd_documento, nm_alias) uses them to download the sentence PDF, and baixar_sentencas(df) does the same for each row of a cjpg DataFrame, adding caminho_sentenca and motivo_falha:
df = tjsp.cjpg("atraso de voo", paginas=1)
df = tjsp.baixar_sentencas(df)
df[["cd_processo", "cd_documento", "caminho_sentenca", "motivo_falha"]]The PDF goes to <diretorio>/sentencas/<cd_processo>_<cd_documento>.pdf. Each sentence takes two requests (cjpg/obterArquivo.do, which redirects to the folder, and the PDF), in any session, spaced by sleep_time. A code outside the eSAJ format raises EntradaInvalidaError before any request; in baixar_sentencas it becomes motivo_falha="entrada_invalida". The other values are nao_pdf, resposta_inesperada, erro_de_gravacao (the PDF could not be written to disk) and the network reasons of juscraper.core.failures.MOTIVOS_FALHA. The cjpg text column decisao already has the sentence text; the PDF keeps the layout and the signatures.
The routes are the ones of tjsp_baixar_doc_movimentacao and tjsp_baixar_sentenca_cjpg in the R package tjsp by José de Jesus Filho. They live in juscraper.courts._esaj.pasta. The movement route answers without login in TJAC, TJAL, TJAM and TJCE as well, but those courts do not have cpopg in juscraper yet.
TJMS has the same cjpg, with the same filters and columns, and the same baixar_sentenca and baixar_sentencas. The 120-character limit of pesquisa (QueryTooLongError) applies only to TJSP, where it was measured. listar_varas and grau="1" in listar_classes and listar_assuntos exist in both courts, which share the cjpg form.
Normalization Utilities
The juscraper.utils.params module provides normalization functions used internally by all scrapers:
normalize_paginas(paginas)— normalizesint | np.integer | list | range | Nonenormalize_pesquisa(pesquisa, **kwargs)— handles deprecated aliasesnormalize_datas(**kwargs)— handles deprecated and generic date aliasescoerce_brazilian_date(value, backend_format)— coerces any of the four supported string formats (ordate/datetime) into the backend’s expected formatler_data_usuario(value)— reads a user-supplied date (the same valuescoerce_brazilian_dateaccepts) as adate, orNonefor anything elseapply_input_pipeline_search(schema_cls, method_name, *, ...)— runs the canonical input pipeline (alias resolution → date coercion → interval validation → pydantic schema) forcjsg/cjpgendpointsiter_date_windows(data_inicio, data_fim, *, max_dias=366, max_anos=None)— splits a date range into non-overlapping windows for auto-chunking;max_anosswitches to calendar-year windowsrun_chunked_search(fetch_window, *, data_inicio, data_fim, dedup_key, ...)— drives a search across windows, concatenates and deduplicatespop_deprecated_alias(kwargs, old, new)andresolve_deprecated_alias(kwargs, old, new, current_value, *, sentinel=None)— accept the old name of a renamed parameter with aDeprecationWarningwarn_unsupported(param_name, tribunal)— deprecated since 0.6.0 (removal in 0.7.0), no replacement: an unsupported parameter raisesTypeErrorvia the schema’sextra="forbid"
pop_deprecated_alias, resolve_deprecated_alias and warn_unsupported live in juscraper.utils.deprecacao; juscraper.utils.params re-exports them.
Per-row failures
Batch methods keep one row per requested item even when the item fails, and say why in the motivo_falha column (None when the item was read). This holds for TJSP cpopg (table basicos) and cposg; for cpopg of TRF1, TRF3, TRF5, TRF6 and TJPE, and cposg of TRF3; for baixar_acordaos, baixar_acordaos_por_processo and baixar_sentencas in the eSAJ courts; and for the batch methods of JusBR and PDPJ. The failures of a call go into a single UserWarning at the end. DataJud contar_processos uses the same values in its error column, without the warning, and "<Class>: <message>" for an error outside them, such as a partial Elasticsearch response.
motivo_falha |
Meaning |
|---|---|
nao_encontrado |
The source says the item does not exist (each scraper documents the signal it reads). |
entrada_invalida |
The input row has no usable value (CNJ, date, code); nothing was requested. |
http_<status> |
The request failed with that HTTP status. |
retry_esgotado_<status> |
The server answered a retryable status until the attempts ran out. |
timeout |
The response did not arrive in time; the profile timeout may be too short. |
conexao |
The connection failed or dropped, also in the middle of the body. |
json_invalido |
The body is not the expected JSON. |
resposta_inesperada |
A page outside the known format, a compressed body that does not decompress, or another error without its own reason. |
nao_pdf |
The PDF endpoint answered with something else; nothing was written. |
sem_acordao |
The process was found, but without an accessible acórdão on that date. |
bloqueio_anti_bot |
A bot manager (Akamai, CloudFront, AWS WAF, F5) challenged or blocked the request. |
captcha_esgotado |
The portal refused the solved captcha in every attempt. |
limite_de_requisicoes |
The service refused the request for too many requests, in a response that is not a retryable status (the TSE full-text service answers HTTP 200 with a text; the TJSP eSAJ, in cpopg and cposg, answers “multiplas consultas simultâneas” in every attempt). Wait and ask again for the failed rows. |
erro_de_gravacao |
The file arrived, but writing it to disk failed with OSError (disk full, no permission on the folder). Used by baixar_acordaos, baixar_acordaos_por_processo, baixar_sentencas, TSE baixar_inteiros_teores and TJSP cpopg/cposg. |
An anti-bot block holds for the whole session. In the PJe cpopg/cposg (TRF1, TRF3, TRF5, TRF6 and TJPE) and in the eSAJ baixar_acordaos, baixar_acordaos_por_processo and baixar_sentencas, the first bloqueio_anti_bot ends the batch: the following rows get the same reason without a request, and the rows already read stay in the result. In baixar_acordaos, baixar_acordaos_por_processo, baixar_sentencas and TSE baixar_inteiros_teores, an erro_de_gravacao ends the batch the same way, because a disk error tends to repeat on the next file: fix the folder and ask again only for the failed rows. The JusBR and PDPJ batch methods go on with the next item. Whenever a row has bloqueio_anti_bot, the warning comes as juscraper.core.exceptions.BloqueioAntiBotWarning, a UserWarning subclass. Wait a few minutes or switch networks, and ask again only for the failed rows. The values live in juscraper.core.failures.MOTIVOS_FALHA.
TRF1, TRF3, TRF5 and TJPE cpopg(..., download_pecas=True), and TRF3 cposg(..., download_pecas=True), also add pecas_falhas, a list per process of {"id": ..., "motivo_falha": ...} for the documents that failed; a failed document does not change the process’s motivo_falha. In TRF1, TRF5 and TJPE, an error writing a document to disk (disk full, no permission) stops that process’s documents: it and the ones not yet requested go to pecas_falhas, the row keeps the detail with motivo_falha resposta_inesperada, and the batch goes on. When the PJe session expires in the middle of a process’s documents, the session is renewed once per process and the remaining documents are requested in the new one. In the TRF1, TRF5 and TJPE cpopg and cpopg_download, renewed sessions that come back expired max_renovacoes_falhas_seguidas times in a row (constructor argument, default 2, None turns it off) end the batch: the following rows get resposta_inesperada (None in cpopg_download) without a request.
Methods whose unit of work has no row to carry the reason (a page, a date window, an alias) raise juscraper.core.exceptions.ColetaParcialError instead of returning a partial result as if it were complete: the eSAJ auto-chunk, TJSP and TJMS cjpg, the paginated cjsg and cjpg of the other courts (see Pagination), ComunicaCNJ listar_comunicacoes, PDPJ pesquisa and DataJud listar_processos. erro.resultado has what was collected, always as a DataFrame of the parsed pages, rows or windows (also when a *_download method, which returns raw pages, raises it), and erro.falhas the failed units with their exceptions (see the cjpg example in the migration guide above).
Rate limiting and retry behaviour
All HTTP scrapers that inherit from juscraper.core.http.HTTPScraper share the same retry loop via _request_with_retry. Defaults:
| Setting | Default | Where to override |
|---|---|---|
| Retried statuses | 403, 429, 500, 502, 503, 504 |
constant RETRYABLE_STATUSES |
| Max attempts | 3 (including the first) |
max_retries= per call |
| Backoff | base_backoff ** attempt → 2s then 4s (sleeps run between attempts 1→2 and 2→3; the 3rd failure raises RetryExhaustedError without sleeping, so the default 8s from 2 ** 3 only kicks in with max_retries >= 4); each wait is capped at max_backoff (300 s) |
base_backoff= per call; max_backoff in politica= (DataJud, JusBR, PDPJ, TRF3, TJMG, TJRS, TJSC) |
| Timeout and dropped connection | Not retried: the first requests.Timeout or requests.ConnectionError is raised |
retry_on_timeout and retry_on_connection_error in politica=, for scrapers with HTTP profiles; already on in the profiles of TJMG, TJRS and TRF3 (both), JusBR and PDPJ (timeout only) and TJSC (connection only) |
Retry-After (numeric seconds) |
Honored when present, capped at max_retry_after (300 s); inf and nan fall back to backoff |
max_retry_after in politica=, for scrapers with HTTP profiles |
Retry-After (HTTP-date) |
Ignored — falls back to backoff (#201) | n/a |
| Inter-request pause | sleep_time=1.0 from the scraper constructor |
jus.scraper("tjsp", sleep_time=5.0) |
TRF6 cpopg does not inherit from HTTPScraper (its lookup is a captcha loop on its own session) and has no HTTP profiles: its request deadline is the constructor argument timeout (default 30 s), as in jus.scraper("trf6", timeout=90), and politica= raises TypeError.
TJSP cpopg and cposg (and their *_download) do not use HTTPScraper either, and both follow the same rule. Each case is tried up to five times, and every attempt runs the search again, because the search is what opens the case in the eSAJ session. A new attempt follows a status in RETRYABLE_STATUSES, a timeout, a dropped connection, the eSAJ error page served with HTTP 200, and the “multiplas consultas simultâneas” notice. The pause between attempts is sleep_time; after that notice it grows to 1, 2, 4 and 8 seconds. Any other 4xx and too many redirects fail on the first attempt. In cpopg, a document already downloaded in an attempt (its page, movements and, with download_pecas=True, its PDFs) is not requested again in the next one; in cposg, only its movements are kept. eSAJ cjpg (TJSP and TJMS) applies the same transport rule to pages 2 onward, with up to five requests per page.
Every scraper rejects an unknown constructor argument with TypeError, so a mistyped name such as sleep_tim= fails at construction instead of being silently ignored.
The exponential backoff (2s then 4s across the three default attempts) resolves transient WAF blocks but does not always escape longer cooldowns. If you see RetryExhaustedError(status_code=403) (or 429) repeatedly on the same scraper:
- First, increase
sleep_timein the constructor so the pause between requests becomes longer than the WAF window. Doubling it (sleep_time=2.0) is usually enough for the TJSP eSAJ WAF. - If that does not help and you are running from a corporate / institutional IP, the block is likely IP-based — switching to a residential network is the only reliable fix.
- The
403retry is global; consumers that can reliably distinguish auth-failure403from WAF403(e.g. PDPJ, where403means expired JWT) keep a local retry loop inaggregators/<name>/download.pyand opt out.