Reconcile all83 observed Semrush URLs and make complete CI verification independent of PyPI
Rebuild V2 candidate verification / candidate (push) Failing after 1m27s
Rebuild V2 candidate verification / candidate (push) Failing after 1m27s
This commit is contained in:
1 parent
44c5797144
commit
e8cef39175
89 files changed
+110412
-1373
No files matched your search
+3
-2
@@ -1,7 +1,8 @@
|
||||
{"_type":"issue","id":"videoreg-7oy.11","title":"V2 CI verification: remove PyPI runtime dependency and reach complete crawl","description":"Actual publicGiteaUI run1321 job1519:types21testsbuild passed; pinnedPythondependencyinstall failed PyPIreadtimeout, completecrawl skipped. This is separate from intentional unresolvedinventoryfailure. ExistingpinnednpmSharpavailable; exactpurePythonparserlicenses canbevendored offline. No app/production changes.","acceptance_criteria":"Real CI reaches completecrawl with0technicalerrors, outputs actualbuildsource identity and expanded258inventory/119unresolved. Do not claim overallPASS or mask restorationblock. Offline parser andfullrasterdecode tested; source unchangedR2.","status":"open","priority":1,"issue_type":"bug","owner":"gavrilovdev@yandex-team.ru","created_at":"2026-10-26T16:03:29Z","created_by":"E.Gavrilov","updated_at":"2026-10-26T16:03:29Z","dependencies":[{"issue_id":"videoreg-7oy.11","depends_on_id":"videoreg-7oy","type":"parent-child","created_at":"2026-10-26T19:03:28Z","created_by":"E.Gavrilov","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"videoreg-7oy.10","title":"V2 public runtime: verify apex and www exact accepted build and trusted TLS","description":"Apex currently resolves77.91.88.137 with trustedTLS HTTP200 but still rejectedV1commit9b5b080. www resolves sameIP but curl60 certificate validation failure. V2 stack apex+www host rule prepared locally, notdeployed before mandatory review/recovery gates. Scope only videoreg service; no globalTraefik/DNS orACME massretry.","acceptance_criteria":"After acceptedV2publish viaexistingGitea/zz path, verify exactimmutableimage and healthcommit, complete representativeHTTPchecks, trustedTLSbothapex/www. Record evidence and keepopenotherwise.","status":"open","priority":1,"issue_type":"task","owner":"gavrilovdev@yandex-team.ru","created_at":"2026-10-26T15:30:38Z","created_by":"E.Gavrilov","updated_at":"2026-10-26T15:30:38Z","dependencies":[{"issue_id":"videoreg-7oy.10","depends_on_id":"videoreg-7oy","type":"parent-child","created_at":"2026-10-26T18:30:38Z","created_by":"E.Gavrilov","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"videoreg-7oy.9","title":"V2 exact Semrush PDF lead: recover complete svk-002-mn.pdf and identify actual document type","description":"Actual Semrush anchor lead1backlink/1domain. OriginalURL http://videoreg.ru/download/svk-002-mn.pdf; CDX20090205154916. HTTP200download473313bytes is malformed:pdfinfo top-levelpagesnull/xref failure, no valid page count. Do not advertise as recovered or relabel anonymousUVR2CH manual. Try other exact original/www/apex dates or legitimate manufacturer duplicate; verify title/model/allpages, PDFstructure/noJavaScript andsourcehash. Keep exact lead unresolved if no complete verified file; fullrelatedmanuals4areseparate.","notes":"Recovered exact full PDF via short-date2009 replay:872857bytes curl0, pdfinfo3pages JSno, scanned pages100–102 read visually by root. Denis Kirin, Mobile News January2008 test, not manual. Immutable raw+render manifest evidence/svk002-review. Validated public copy queued; companion/content-manager review and HTTPsamehash pending before closure.","status":"closed","priority":1,"issue_type":"task","owner":"gavrilovdev@yandex-team.ru","created_at":"2026-10-26T14:47:06Z","created_by":"E.Gavrilov","updated_at":"2026-10-26T15:28:45Z","closed_at":"2026-10-26T15:28:45Z","close_reason":"Recovered full exact872857byte3page SVK002 MobileNewsJan2008 test; root+contentmanager read100–102pixels, authorattribution andusefulcompanionpublishedlocally. PDFnoJSvalid, HTTP200matchesfullsourceSHA; evidence/svk002-review/manifest.json + downloads-http.json. Earliercorrupt/truncatedcopiesnotpublic.","labels":["blocking","pdf","recovery","semrush"],"dependencies":[{"issue_id":"videoreg-7oy.9","depends_on_id":"videoreg-7oy","type":"parent-child","created_at":"2026-10-26T17:47:05Z","created_by":"E.Gavrilov","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"videoreg-7oy.8","title":"V2 restoration blocker: recover unresolved historic bodies and important media","description":"Full CDX yielded883HTMLcaptures,121HTML URLkeys,259resource URLkeys;25realHTMLbodies fetched after all distinct pre/post2015 snapshots and www/apexvariants. Known inventory170normalizedURLs includes59unresolved content leads plus1partial listing, and important installation/examplevideo media remain unavailable. Keep explicit unresolved coverage rather than modern substitutes. Some HTTP200media invalid: directSVK002PDF structurally corrupt; only2ZIP-contained manuals valid. Continue linked-source/alternatearchive and mandatorySemrush work. Acceptance: each meaningful URL reconciled to real edited body, evidenced equivalent, genuine spam/commercial exclusion, or concrete external blocker; missing mandatory recovery not optional followup or PASS.","notes":"R2candidate4a0d828 source30actualHTML+28typedpages+5completePDFs+162originalJPEGframes. Completecrawl technical0errors, BUT238knownURLs/138nonexcluded:99unresolved(96bodies/3listings)+1partialGPSZIP; primaryresources136:62unfetched+1invalid, samplehost25JPEGmissing. These remain mandatory blockers; not generic substitutions or optionalfollowup. Rawattempts/immutablebytes inventories retained.","status":"open","priority":1,"issue_type":"task","owner":"gavrilovdev@yandex-team.ru","created_at":"2026-10-26T13:59:42Z","created_by":"E.Gavrilov","updated_at":"2026-10-26T15:46:07Z","labels":["archive","blocking","restoration"],"dependencies":[{"issue_id":"videoreg-7oy.8","depends_on_id":"videoreg-7oy","type":"parent-child","created_at":"2026-10-26T16:59:41Z","created_by":"E.Gavrilov","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"videoreg-7oy.7","title":"V2 required: reconcile Noxtools Semrush backlink targets with complete videoreg inventory","description":"Direct user requirement: root coordinator inspects Semrush in shared in-app Noxtools session sequentially. Prepare lost URL/title/questions under docs/rebuild-v2/semrush. Consume actual root exports site-restoration-status/semrush-recovery/videoreg.ru, individually assess target URLs/anchors/referring contexts, add legitimate new paths to inventory and fetch real bodies/snapshots. Backlinks are leads only, not recovered text or source truth. No invented Semrush results; no takeover of shared browser. Acceptance: actual provided export scope documented, each legitimate new target reconciled/restored or explicit unresolved blocker, full editorial/outbound gate repeated.","notes":"Actualcoordinatorfilesingested:Indexed89reported83DOM17transcribed;Anchors52DOM3transcribed;LostVital18DOM6transcribed.5referrersattempted3HTTP200,2unavailable. ExactPDFlead recovered3pMobileNewsJan2008test notmanual,.9closedwithHTTPsamehash. Fullrowcoverage/remainingreferrersandmissingbodies remainmandatoryblocked. No sharedbrowser takeover.","status":"in_progress","priority":1,"issue_type":"task","owner":"gavrilovdev@yandex-team.ru","created_at":"2026-10-26T13:49:39Z","created_by":"E.Gavrilov","updated_at":"2026-10-26T15:46:08Z","started_at":"2026-10-26T14:35:25Z","labels":["blocking","recovery","semrush"],"dependencies":[{"issue_id":"videoreg-7oy.7","depends_on_id":"videoreg-7oy","type":"parent-child","created_at":"2026-10-26T16:49:39Z","created_by":"E.Gavrilov","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"videoreg-7oy.8","title":"V2 restoration blocker: recover unresolved historic bodies and important media","description":"Full CDX yielded883HTMLcaptures,121HTML URLkeys,259resource URLkeys;25realHTMLbodies fetched after all distinct pre/post2015 snapshots and www/apexvariants. Known inventory170normalizedURLs includes59unresolved content leads plus1partial listing, and important installation/examplevideo media remain unavailable. Keep explicit unresolved coverage rather than modern substitutes. Some HTTP200media invalid: directSVK002PDF structurally corrupt; only2ZIP-contained manuals valid. Continue linked-source/alternatearchive and mandatorySemrush work. Acceptance: each meaningful URL reconciled to real edited body, evidenced equivalent, genuine spam/commercial exclusion, or concrete external blocker; missing mandatory recovery not optional followup or PASS.","notes":"Expandedknowninventory258/nonexcluded158:119unresolved =99baseline +20newSemrush epoch/fragment/encoded/malformedleads. ActualR2app/exportunchanged,5rolesapprovedscopedsubsetonly. Primaryresources63missing/invalid,25sampleframesmissing,1partialZIPremain. Nextprioritybatch3actualtargets tried,0newvalidatedbodies; no bulkretry/no429. Notoptional/complete.","status":"open","priority":1,"issue_type":"task","owner":"gavrilovdev@yandex-team.ru","created_at":"2026-10-26T13:59:42Z","created_by":"E.Gavrilov","updated_at":"2026-10-26T16:05:13Z","labels":["archive","blocking","restoration"],"dependencies":[{"issue_id":"videoreg-7oy.8","depends_on_id":"videoreg-7oy","type":"parent-child","created_at":"2026-10-26T16:59:41Z","created_by":"E.Gavrilov","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"videoreg-7oy.7","title":"V2 required: reconcile Noxtools Semrush backlink targets with complete videoreg inventory","description":"Direct user requirement: root coordinator inspects Semrush in shared in-app Noxtools session sequentially. Prepare lost URL/title/questions under docs/rebuild-v2/semrush. Consume actual root exports site-restoration-status/semrush-recovery/videoreg.ru, individually assess target URLs/anchors/referring contexts, add legitimate new paths to inventory and fetch real bodies/snapshots. Backlinks are leads only, not recovered text or source truth. No invented Semrush results; no takeover of shared browser. Acceptance: actual provided export scope documented, each legitimate new target reconciled/restored or explicit unresolved blocker, full editorial/outbound gate repeated.","notes":"All83actualobservedIndexedPageURLs now reconciled inexactorder;17metadataonly,89reported/6unseen. Inventory238→258 adds20unresolvedtargets;32exactURLvariants epochunknown notassumedBloxspam. Per83 dispositions/sha andbounded3target7requestrecoverybatch saved. topic196CDX[], product138archive404wrappers,ZIPtransportfailure;0newbodies,0HTTP429. Anchors3/52 LostVital6/18stillpartial. FullSemrush/recoverymandatoryopen.","status":"in_progress","priority":1,"issue_type":"task","owner":"gavrilovdev@yandex-team.ru","created_at":"2026-10-26T13:49:39Z","created_by":"E.Gavrilov","updated_at":"2026-10-26T16:05:12Z","started_at":"2026-10-26T14:35:25Z","labels":["blocking","recovery","semrush"],"dependencies":[{"issue_id":"videoreg-7oy.7","depends_on_id":"videoreg-7oy","type":"parent-child","created_at":"2026-10-26T16:49:39Z","created_by":"E.Gavrilov","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"videoreg-7oy.6","title":"V2 illustrator veto: replace generic hero with inspected technical diagrams in recovered SVK pages","description":"Actual V1 pixels inspected: home-1440.png, home-360.png, guides-choose-360.png under docs/rebuild-v2/evidence/designer-initial. Hero depicts a generic camera and provides no explanation of recovered original SVK design. Recovered auto20070228153116 full cp1251 body describes one/two USB cameras, SVK recorder, FLASH media and Windows viewing; distinct road/guard modes. Existing article has no explanatory visuals or actual integrated V2 candidate proof. This blocks V2 illustration acceptance.","design":"Options: retain decorative camera; use only low-resolution archived photographs; add precise mobile-first explanatory diagrams alongside selected recovered photographs. Chosen compromise: two original SVG diagrams for signal chain and relative road/guard capture cadence, with model-specific context and no invented wiring instructions or rate claims. Root integrates these only where the body discusses them; metadata remains internal.","acceptance_criteria":"Open both actual SVG renderings and inspect their exact integrated candidate pages at narrow and wide widths; verify legible labels, crop/layout, alt text, intrinsic size/load, no external references, subject consistency with auto snapshot; record URL, screenshot paths and candidate source/build hash. No final PASS before integrated pixels are viewed.","notes":"R2 same-reviewer verification completed for exactsource4a0d828ef070d305bea57d6a5d16d612fc16a0e2 app72adaeab317c83069c2ca92599940955372768776367da42b26ed0a7d521e822 exportadb919f431cb965359d7297194dbec7115c19dc8f0ddbe8340f303a2f1531603. Opened all7changed actual R2 screenshots plus5nativegallery crops. Rehashed68ss+18appsourcefiles;61R1pixel-identical,182publicassetblobs unchanged, all3SVG/CSS/articleJSON/figuregallerysourceunchanged. No new illustration defect; .6 stays scopedclosed. FinalR2evidence illustrator-final-r2/verdict.json +delta-manifest.json and appended illustrator-candidate.md. Whole-site/corpus acceptance explicitly NOT granted; mandatory unresolved99corpus remains separate.","status":"closed","priority":1,"issue_type":"task","owner":"gavrilovdev@yandex-team.ru","created_at":"2026-10-26T13:20:47Z","created_by":"E.Gavrilov","updated_at":"2026-10-26T15:45:58Z","started_at":"2026-10-26T13:22:20Z","closed_at":"2026-10-26T15:33:30Z","close_reason":"Same illustrator verified exactcandidate integrated diagrams/photos at360/1440, alt/ratios/load and gallery6→30 actualframes. Subject-specific illustration finding resolved; whole-site/corpus acceptance remains blocked separately.","labels":["blocking","role-illustrator","v2"],"dependencies":[{"issue_id":"videoreg-7oy.6","depends_on_id":"videoreg-7oy","type":"parent-child","created_at":"2026-10-26T16:20:47Z","created_by":"E.Gavrilov","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"videoreg-7oy.5","title":"V2 creative veto: replace generic shopping journey with coherent SVK technical library","description":"Independent V2 audit opened all six baseline layouts at narrow and wide widths using actual captured pixels in docs/rebuild-v2/evidence/designer-initial and fetched live baseline pages at50541. Homepage still leads with generic dashcam buying slogan, four modern paragraph guides, unrelated 2026 seller catalog and decorative camera; recovered auto20070228153116 is specifically SVK/VR-001 ≤5fps USB-camera+FLASH hardware with operating modes and installation examples. Thus subject, visual language and user journey do not match recovered corpus. Process/date/provenance badges and the seller-catalog block compete with reader needs. No substantive library/article/media templates exist for actual historical content; old auto redirect is semantically wrong.","design":"Options: keep modern generic landing and append archive links; mimic obsolete commercial brochure; or use a technical-library editorial direction. Chosen compromise: technical library with a compact factual hardware visual, distinct paths for identifying the recorder, modes/FAQ, installation examples and reading recorded files; recovered product facts remain historically scoped, modern practice/tool pages subordinate and clearly applicable. Retain useful material, remove sales CTAs/process decoration. Typography and diagram/photo use must serve long technical articles rather than repeated empty cover cards.","acceptance_criteria":"Review exact V2 candidate homepage, listings/search, long/short recovered pages, table/image-heavy templates, tool and404 at360 and1440 with independently opened screenshots bound to build hash. Homepage/navigation and related links must expose recovered SVK corpus with coherent journeys; images clarify actual subject; no misleading current shop posture or repetitive production-process badges. Calculator must state applicability to stream bitrate and not imply that SVK JPEG/frame recording has the same input model unless actual frame-size mode is implemented. No final PASS until corpus/editorial/visual gaps are actually resolved.","notes":"R2 exactsource4a0d828, appSHA72adaeab, exportadb919f. Independent view28R1pixels,7newR2pixels; actual-byte comparison25/28reviewedviewsidentical,3changedreviewedviewsallreopened.14liveHTTPpageschecked. Historical technical-library direction/modelscoping/subjectvisuals/JPEGvsstream journey resolved. Genuine R1home formula ambiguity fixed with explicit full denominator+reserve and actually viewed360/1440+source/liveHTML. Report docs/rebuild-v2/reviews/creative-candidate.md and creative-r1/r2evidence. Close onlycreative-direction veto; overall corpus99+Semrush mandatoryblocks remain open, no site/publication PASS.","status":"closed","priority":1,"issue_type":"task","owner":"gavrilovdev@yandex-team.ru","created_at":"2026-10-26T13:20:14Z","created_by":"E.Gavrilov","updated_at":"2026-10-26T15:39:34Z","started_at":"2026-10-26T13:21:28Z","closed_at":"2026-10-26T15:39:34Z","close_reason":"Same creative reviewer verified exact R2 library direction, meaningful imagery, scoped models/JPEGtool and corrected homepage formula; role-specific veto resolved. Mandatory unresolved corpus/Semrush and overall publication remain blocked separately.","labels":["blocking","role-creative-director","v2"],"dependencies":[{"issue_id":"videoreg-7oy.5","depends_on_id":"videoreg-7oy","type":"parent-child","created_at":"2026-10-26T16:20:13Z","created_by":"E.Gavrilov","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"videoreg-7oy.4","title":"V2 programmer veto: replace sampled smoke with complete corpus and outbound verification","description":"Baseline056f1a6 deploy/smoke-static.py15 hardcodes ten URLs;27-34 parses only this seed set and fetches extra links without recursive parsing;12-14 ignores external and absolute same-origin URLs, srcset/action/CSS/script contexts. No archive URL inventory is consumed, no body/hash/duplicate or outbound-ledger gate exists. nginx.conf11 and serve-local.py14-15 redirect historic /auto.shtml to new generic choose although docs/provenance.json12-21 explicitly records no recovered body. Thus prior25/25 cannot substantiate corpus restoration or equivalent legacy routing.","design":"Options: keep sampled smoke as endpoint health only; or introduce complete exported-site+inventory reconciliation with a distinct evaluated outbound ledger and clear known failure reports. Chosen compromise proposed: retain useful small health smoke but name it narrowly; add deterministic complete crawler driven by output manifest and discovered URLs, reconcile every historical URL and audit each external occurrence. Publish no equivalence redirect without source evidence; unresolved bodies remain mandatory blockers.","acceptance_criteria":"For exact V2 source/build hash, enumerate complete generated HTML set and discovered meaningful archive URLs; recursively check all internal links/fragments/assets including new pages; reconcile every inventory item to restored/equivalent/explicit-exclusion/unresolved, never count unresolved as recovered. Extract href/src/srcset/action, CSS url and script destinations from source/build/DOM and match each external occurrence to reviewed keep/remove reason. Report missing/thin/duplicate/error bodies and real404. Test legacy destination substantive equivalence or keep unresolved without false redirect. Independent programmer review reads code/diff and re-runs resulting checks; unresolved archive corpus blocks full V2 acceptance.","notes":"Exact independent review source d0fd706, app manifest bd8027c94de4dd943fcbd5f42dd2f907746b2ac63d3d9174401859180b3aff24 and export4c1c42a4465165e33e947fdf595804d63d4735aefb5f6aba2f419118d143d1dd matched owner. Complete checker now implemented and independently repeated:35HTML33content130HTTP1116refs168raster15external occurrences,0technicalerrors,all28typedarticlesexported.238inventoryitems still99unresolved: restoration remains mandatoryBLOCKED; not relabelled follow-up. Exactreport docs/rebuild-v2/reviews/programmer-candidate.md and independent evidence programmer-built-crawl.json. No final V2PASS.\nR2 same-reviewer delta audit: actualdiff d0fd706..4a0d828 read; formula includesreserve+cams, fullbodysearch includescode+linklabels. Independent R2crawl exactappSHA72adaeab... andexportadb919f4... matched:35HTML130HTTP1116refs168rasters0errors99unresolved. See programmer-candidate.md R2appendix and programmer-built-crawl-r2.json. .4 remainsBLOCKED mandatorycorpus; noV2PASS.","status":"blocked","priority":1,"issue_type":"bug","owner":"gavrilovdev@yandex-team.ru","created_at":"2026-10-26T13:15:48Z","created_by":"E.Gavrilov","updated_at":"2026-10-26T15:39:12Z","started_at":"2026-10-26T13:27:19Z","labels":["blocking","role-programmer-expert","v2"],"dependencies":[{"issue_id":"videoreg-7oy.4","depends_on_id":"videoreg-7oy","type":"parent-child","created_at":"2026-10-26T16:15:47Z","created_by":"E.Gavrilov","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
|
||||
@@ -17,20 +17,24 @@ jobs:
|
||||
COMMIT_SHA: ${{ github.sha }}
|
||||
NEXT_TELEMETRY_DISABLED: "1"
|
||||
run: npm run ci:quality
|
||||
- name: Install pinned recovery verification dependencies
|
||||
- name: Verify offline pinned checker dependencies and raster failure behavior
|
||||
run: |
|
||||
python3 -m venv .local-run/recovery-env
|
||||
.local-run/recovery-env/bin/python -m pip install --disable-pip-version-check -r scripts/rebuild-v2/requirements.txt
|
||||
python3 -S scripts/rebuild-v2/verify-vendor.py
|
||||
node scripts/rebuild-v2/check-raster-sharp.mjs
|
||||
- name: Validate complete export and safe preview
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
py=.local-run/recovery-env/bin/python
|
||||
"$py" scripts/rebuild-v2/check-preview.py
|
||||
"$py" deploy/serve-local.py > "${RUNNER_TEMP}/videoreg-v2-preview.log" 2>&1 &
|
||||
export PYTHONPATH="$PWD/scripts/rebuild-v2/vendor"
|
||||
export PYTHONDONTWRITEBYTECODE=1
|
||||
export VIDEOREG_RASTER_DECODER=sharp
|
||||
py=python3
|
||||
"$py" -S scripts/rebuild-v2/check-preview.py
|
||||
"$py" -S scripts/rebuild-v2/check-fetch-rate-limit.py
|
||||
"$py" -S deploy/serve-local.py > "${RUNNER_TEMP}/videoreg-v2-preview.log" 2>&1 &
|
||||
preview_pid=$!
|
||||
trap 'kill "$preview_pid" 2>/dev/null || true' EXIT
|
||||
base=$("$py" - "$preview_pid" <<'PYREADY'
|
||||
base=$("$py" -S - "$preview_pid" <<'PYREADY'
|
||||
import json, pathlib, sys, time, urllib.request
|
||||
expected_pid = int(sys.argv[1])
|
||||
for attempt in range(50):
|
||||
@@ -48,7 +52,7 @@ jobs:
|
||||
raise SystemExit('Candidate preview did not become ready')
|
||||
PYREADY
|
||||
)
|
||||
"$py" scripts/rebuild-v2/check-built.py --base "$base"
|
||||
"$py" -S scripts/rebuild-v2/check-built.py --base "$base"
|
||||
- name: Record verification identity and failures in job log
|
||||
if: always()
|
||||
run: |
|
||||
@@ -57,7 +61,7 @@ jobs:
|
||||
path = pathlib.Path('docs/rebuild-v2/evidence/built-crawl.json')
|
||||
if path.is_file():
|
||||
data = json.loads(path.read_text())
|
||||
print(json.dumps({key: data.get(key) for key in ('sourceCommit', 'sourceManifestSha256', 'exportManifestSha256', 'summary', 'errors')}, ensure_ascii=False, indent=2))
|
||||
print(json.dumps({key: data.get(key) for key in ('sourceCommit', 'repositoryHead', 'builtSourceManifestSha256', 'sourceManifestSha256', 'exportManifestSha256', 'rasterDecoder', 'summary', 'errors')}, ensure_ascii=False, indent=2))
|
||||
else:
|
||||
print('No complete crawl report: inspect earlier setup/build failure')
|
||||
PYREPORT
|
||||
+11
-3
@@ -21,7 +21,7 @@ CDX вернул 883 HTML captures, 121 collapsed HTML URL key и 259 resource U
|
||||
|
||||
Опубликованы 28 typed материалов, в том числе сопроводительные страницы документов и галерей; это не 28 восстановленных исторических HTML-статей. Есть четыре полных исходных инструкции (37 страниц), полный тест Дениса Кирина «СВК-002», «Мобильные новости», январь 2008, страницы 100–102, и 162 исходных JPEG (158 из шести альбомов + четыре полностью спасённых члена повреждённого ZIP). Все три страницы журнального теста действительно прочитаны по пикселям; ранние обрезанные копии не публикуются. Документ `svk-002-mn.pdf` — **журнальный тест, не инструкция**.
|
||||
|
||||
Обязательные пробелы: **99 unresolved HTML/linked entries** (96 тел/3 listing), один частично восстановленный ZIP, 63 отсутствующих/невалидных ресурса основного домена и 25 JPEG внешнего исходного sample-host. Повреждённый ZIP не предлагается как полный: опубликованы только четыре члена с проверенными размером/CRC и декодированием. Нестандартные EXIF GPS tags не объявлены валидными координатами.
|
||||
Обязательные пробелы: **119 unresolved targets** (99 прежних HTML/linked entries плюс20 новых Semrush epoch/fragment/query/path leads), один частично восстановленный ZIP, 63 отсутствующих/невалидных ресурса основного домена и 25 JPEG внешнего исходного sample-host. Повреждённый ZIP не предлагается как полный: опубликованы только четыре члена с проверенными размером/CRC и декодированием. Нестандартные EXIF GPS tags не объявлены валидными координатами.
|
||||
|
||||
## Редактура и ссылки
|
||||
|
||||
@@ -46,7 +46,7 @@ R1 нашёл два последующих дефекта: неоднознач
|
||||
## Проверки R2
|
||||
|
||||
- `npm run ci:quality`: types, 21 существующий тест, static build — PASS. Это не проверка старого ingestion/БД в production. [Quality log](docs/rebuild-v2/evidence/quality-r2.log), [final SHA build](docs/rebuild-v2/evidence/build-r2-final-sha.log).
|
||||
- Полный crawler: **35 HTML / 33 content pages, 130 HTTP, 1116 local references, 168 decoded raster assets, 0 technical errors**. [Python preview](docs/rebuild-v2/evidence/built-crawl.json), [nginx R2](docs/rebuild-v2/evidence/nginx-crawl-r2.json). Exit status намеренно nonzero из-за незавершённого восстановления; технический PASS не объявляется приёмкой сайта.
|
||||
- Полный crawler: **35 HTML / 33 content pages, 131 HTTP, 1116 local references, 168 fully decoded raster assets, 0 technical errors**. [Python preview](docs/rebuild-v2/evidence/built-crawl.json), [nginx R2](docs/rebuild-v2/evidence/nginx-crawl-r2.json). Exit status намеренно nonzero из-за незавершённого восстановления; технический PASS не объявляется приёмкой сайта.
|
||||
- [68 реальных снимков](docs/rebuild-v2/evidence/candidate-r2/browser-pages.json), 34 URL × 360/1440 px: 0 document overflow, 0 broken images, 0 runtime errors. 61/68 screenshot hashes совпадают с R1; все семь изменённых представлений действительно пересмотрены.
|
||||
- [15 browser checks](docs/rebuild-v2/evidence/candidate-r2/browser-functional.json): full text/code/link-label/category search, empty/reset, keyboard, JPEG=1000 seconds, stream=23040 seconds, invalid inputs, gallery 6→30 и настоящий 404. Дизайнер дополнительно независимо проверил skip-link и горизонтальную прокрутку таблицы клавиатурой.
|
||||
- Все [девять PDF/ZIP](docs/rebuild-v2/evidence/downloads-http.json) получены через настоящий nginx с HTTP200 и побайтовым совпадением export. Невалидные архивы не публикуются.
|
||||
@@ -57,7 +57,7 @@ R1 нашёл два последующих дефекта: неоднознач
|
||||
|
||||
[Reconciliation](docs/rebuild-v2/semrush/reconciliation.json), [scope](docs/rebuild-v2/semrush/scope.md), [actual referrers](docs/rebuild-v2/semrush/referrer-verification.json).
|
||||
|
||||
Noxtools browser контролирует coordinator. Получены реальные транскрипции: Indexed Pages — 17 из 89 reported (83 DOM); Anchors — 3 из 52; Lost and Vital — 6 из 18. Самостоятельно запрошены пять конкретных referring URLs: три HTTP200, два недоступны. Метрики/first-last seen не выдаются за оригинальные тела или даты публикации. Поздний Blox/domain-expiry spam исключён. Полная выгрузка, оставшиеся contexts и обязательные recovery followups не завершены: **`videoreg-7oy.7` OPEN**.
|
||||
Noxtools browser контролирует coordinator. Получены реальные транскрипции: Indexed Pages — 17 из 89 reported (83 DOM); Anchors — 3 из 52; Lost and Vital — 6 из 18. Самостоятельно запрошены пять конкретных referring URLs: три HTTP200, два недоступны. Метрики/first-last seen не выдаются за оригинальные тела или даты публикации. Поздние похожие на Blox/domain-expiry URL без actual body не считаются доказанным спамом; они сохранены unresolved-epoch. Получен exactURL transcript всех83наблюдённыхURL, сверенный в indexed83-reconciliation.json; metadata остаются только17, шесть заявленных URL не наблюдались. Полные metadata, оставшиеся contexts и обязательные recovery followups не завершены: **`videoreg-7oy.7` OPEN**.
|
||||
|
||||
## Публичный runtime: V1, не V2
|
||||
|
||||
@@ -77,3 +77,11 @@ playwright-cli -s=videoreg-v2 --raw run-code --filename=scripts/rebuild-v2/brows
|
||||
```
|
||||
|
||||
Новый build необходимо снова идентифицировать и проверить; случайные build IDs могут менять export hash. Не используйте отклонённый V1 smoke с фиксированными guide URLs как V2 acceptance.
|
||||
|
||||
## Дополнение:83URL и первый remote CI
|
||||
|
||||
После пяти scoped reviews coordinator передал полный URL-only transcript83, без новых metadata. Inventory расширен238→258; исходные18appfiles и R2export не менялись. Новые20целей остаются unresolved, в том числе неизвестная эпоха17путей, fragmentS1, encodedcamera path и malformedcategory79%29. Изначальные role reports указывают99baseline gaps на момент просмотра; текущих unresolved уже119.
|
||||
|
||||
Ограниченный recovery-пакет: topic196 «Применение доказательств» (контекст реального forumf2 listing), product138 «СВК-005» (реальная category79) и отдельная hyphenZIPинструкция. Два CDXзапроса и максимумпятьreplays, без massretry: новыевалидные тела0, HTTP429не наблюдалось. [Фактические попытки](docs/rebuild-v2/semrush/priority83-recovery-batch.json).
|
||||
|
||||
Remote CI run1321 для44c5797 фактически наблюдён через публичныйGiteaUI: types/21tests/build прошли, fullcrawl не запускался из-заPyPIreadtimeouts при pinneddependencies. Это самостоятельная CIпроблема, не ожидаемый inventoryexit1. Offlineverificationfix и его повторный CI отслеживаются отдельно, без изменения приложения.
|
||||
@@ -26,3 +26,5 @@ Preview по умолчанию выбирает свободный случай
|
||||
Публичный runtime — статический export в nginx; Node.js и старый ingestion в нём не запускаются. Gitea-ветка `codex/videoreg-rebuild-v2` проверяет кандидат без deployment. `master` использует существующий изолированный stack `videoreg` на `zz`. Публикация V2 выполняется после обязательной приёмки, которая сейчас заблокирована. Текущий production всё ещё V1.
|
||||
|
||||
Не используйте старый `deploy/smoke-static.py` как V2 gate: он относится к отклонённому V1. Актуальная полная проверка — `scripts/rebuild-v2/check-built.py`. Исторические исходники и их попытки восстановления сохранены вне публикуемого дерева; архивный HTML/JavaScript не исполняется и не вставляется в страницы.
|
||||
|
||||
CI-проверка работает без PyPI: `PYTHONPATH=scripts/rebuild-v2/vendor VIDEOREG_RASTER_DECODER=sharp python3 -S scripts/rebuild-v2/check-built.py --base http://127.0.0.1:50541`. Vendored pure Python sources имеют исходные лицензии и SHA manifest; raster decoder использует существующий pinned sharp из npm lockfile и действительно декодирует пиксели. Проверки нельзя отключить.
|
||||
+27
-13
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"domain": "videoreg.ru",
|
||||
"epic": "videoreg-7oy",
|
||||
"updatedAt": "2026-10-26T15:49:49.658757+00:00",
|
||||
"updatedAt": "2026-10-26T16:08:30.450797+00:00",
|
||||
"stage": "candidate-R2-five-role-reviewed; restoration-blocked",
|
||||
"v1Acceptance": "user rejected; all prior PASS superseded",
|
||||
"rollbackRef": "videoreg-v1-rejected-20261026",
|
||||
@@ -34,10 +34,11 @@
|
||||
"additionalSampleHostJpegDecoded": 158,
|
||||
"salvagedCompleteGpsJpeg": 4,
|
||||
"originalSampleFramesUnavailable": 25,
|
||||
"knownUrlInventory": 238,
|
||||
"meaningfulNonExcludedUrls": 138,
|
||||
"knownUrlInventory": 258,
|
||||
"meaningfulNonExcludedUrls": 158,
|
||||
"publicationCounts": {
|
||||
"edited-recovered": 20,
|
||||
"unresolved-epoch": 17,
|
||||
"unresolved": 96,
|
||||
"recovered-document": 5,
|
||||
"partial-media-recovery": 1,
|
||||
@@ -45,15 +46,19 @@
|
||||
"replacement-navigation": 2,
|
||||
"unresolved-listing": 3,
|
||||
"verified-equivalent": 11,
|
||||
"excluded-commercial": 4
|
||||
"unresolved-fragment": 1,
|
||||
"unresolved-encoded-path": 1,
|
||||
"excluded-commercial": 4,
|
||||
"unresolved-malformed-query": 1
|
||||
},
|
||||
"inventoryComplete": false
|
||||
},
|
||||
"defects": [
|
||||
"videoreg-7oy.8:99unresolvedHTML/linked inventory entries plus1partialGPSZIP,63unresolvedprimarymediaresources and25sampleJPEG gaps; no fabricated bodies",
|
||||
"videoreg-7oy.7:Semrush actualtranscriptionspartial Indexed17/89,Anchors3/52,LostVital6/18; fullreconciliationblocked",
|
||||
"videoreg-7oy.4/.1:wholecorpusandeditorialacceptanceblocked; specificpublishedsubset reviewed",
|
||||
"videoreg-7oy.10:V2notdeployed; publicapextrustedTLS200stillV1;wwwcurl60"
|
||||
"videoreg-7oy.8:119unresolvedtargets(99baselineHTML/linked +20newSemrushunverifiedepoch/fragment/query/path) plus1partialGPSZIP,63unresolvedprimarymediaresources and25sampleJPEG gaps; no fabricated bodies",
|
||||
"videoreg-7oy.7:Semrush actualtranscriptionspartial Indexed83exactURLs/89reported,17metadata;Anchors3/52,LostVital6/18; fullreconciliationblocked",
|
||||
"videoreg-7oy.4/.1:wholecorpusandeditorialacceptanceblocked119targets; specificpublishedsubset reviewed",
|
||||
"videoreg-7oy.10:V2notdeployed; publicapextrustedTLS200stillV1;wwwcurl60",
|
||||
"videoreg-7oy.11:remoteCI1321failedPyPIreadtimeout; offlineverificationfixinprogress"
|
||||
],
|
||||
"local": {
|
||||
"port": 50541,
|
||||
@@ -69,12 +74,12 @@
|
||||
"acceptance": "blocked",
|
||||
"htmlFiles": 35,
|
||||
"contentPages": 33,
|
||||
"HTTPRequests": 130,
|
||||
"HTTPRequests": 131,
|
||||
"localReferences": 1116,
|
||||
"emittedExternalOccurrences": 15,
|
||||
"activeSourceFiles": 18,
|
||||
"inventoryItems": 238,
|
||||
"unresolvedInventoryItems": 99,
|
||||
"inventoryItems": 258,
|
||||
"unresolvedInventoryItems": 119,
|
||||
"suspiciousPages": 0,
|
||||
"errors": 0,
|
||||
"decodedRasterAssets": 168
|
||||
@@ -98,7 +103,14 @@
|
||||
"docs/rebuild-v2/outbound-links.json",
|
||||
"docs/rebuild-v2/evidence/built-crawl.json",
|
||||
"docs/rebuild-v2/evidence/candidate-r2/browser-pages.json",
|
||||
"docs/rebuild-v2/semrush/reconciliation.json"
|
||||
"docs/rebuild-v2/semrush/reconciliation.json",
|
||||
"docs/rebuild-v2/semrush/indexed83-reconciliation.json",
|
||||
"docs/rebuild-v2/semrush/priority83-recovery-batch.json",
|
||||
"docs/rebuild-v2/reviews/designer-original-reviewer-final.md",
|
||||
"docs/rebuild-v2/reviews/creative-candidate.md",
|
||||
"docs/rebuild-v2/reviews/content-candidate.md",
|
||||
"docs/rebuild-v2/reviews/illustrator-candidate.md",
|
||||
"docs/rebuild-v2/reviews/programmer-candidate.md"
|
||||
],
|
||||
"production": {
|
||||
"v2Deployed": false,
|
||||
@@ -112,7 +124,9 @@
|
||||
"indexed": {
|
||||
"reported": 89,
|
||||
"DOM": 83,
|
||||
"transcribed": 17
|
||||
"urlRowsTranscribed": 83,
|
||||
"metadataRowsTranscribed": 17,
|
||||
"reportedButUnseen": 6
|
||||
},
|
||||
"anchors": {
|
||||
"reported": 52,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
CDX discovery: 883 HTML captures across 2007–2025; 121 collapsed HTML URL keys and 259 resource URL keys. Removing phpBB sid duplicates gives101 original normalized HTML URLs. Full CDX JSON has no resume key, so returned index is complete for the actual query (all883 originals were HTTP;528www and355apex; no HTTPS200 captures returned). Linked original URLs from every fetched body expand the known inventory. Unfetched bodies may contain further undiscovered links: this is a **known lower bound**, not a complete historical-site claim.
|
||||
|
||||
Known normalized URLs in inventory: **238**. Meaningful/non-utility denominator (including unresolved): **138**. Actual validated fetched HTML bodies: **30** (includes commercial/navigation pages; not all are published articles). Publication dispositions:
|
||||
Known normalized URLs in inventory: **258**. Meaningful/non-utility denominator (including unresolved): **158**. Actual validated fetched HTML bodies: **30** (includes commercial/navigation pages; not all are published articles). Publication dispositions:
|
||||
|
||||
- edited-recovered: 20
|
||||
- excluded-commercial: 4
|
||||
@@ -11,9 +11,17 @@ Known normalized URLs in inventory: **238**. Meaningful/non-utility denominator
|
||||
- recovered-document: 5
|
||||
- replacement-navigation: 2
|
||||
- unresolved: 96
|
||||
- unresolved-encoded-path: 1
|
||||
- unresolved-epoch: 17
|
||||
- unresolved-fragment: 1
|
||||
- unresolved-listing: 3
|
||||
- unresolved-malformed-query: 1
|
||||
- verified-equivalent: 11
|
||||
|
||||
Each entry has URL/type/snapshot/raw hash/title/body size/destination/editorial action/status/reason in `url-inventory.json`. `edited-recovered` counts source URLs, not unique articles; canonical merges and verified equivalents are separate. Typed article pages include new HTML document companions whose complete original PDFs are available; counts must not be presented as16 historic HTML bodies.
|
||||
|
||||
Important unresolved items include missing historical topic bodies, original installation photographs, unrecovered video bytes and partial GPSsampleZIP. The January2008 SVK002 journal test PDF is now completely recovered (3pages). All alternative versions and URL variants actually attempted are in raw/requests.jsonl. These gaps and pending Semrush reconciliation remain mandatory V2 blockers. No historical article is synthesized from a backlink anchor/title. V1 modern guides/retail cards do not enter recovery counts.
|
||||
Important unresolved items include missing historical topic bodies, original installation photographs, unrecovered video bytes and partial GPSsampleZIP. The January2008 SVK002 journal test PDF is now completely recovered (3pages). All alternative versions and URL variants actually attempted are in raw/requests.jsonl. Semrush83URLtranscript adds explicit epoch/encoded/malformed/fragment-unverified leads; no URL-only Blox/spam exclusion is assumed. These gaps and pending Semrush reconciliation remain mandatory V2 blockers. No historical article is synthesized from a backlink anchor/title. V1 modern guides/retail cards do not enter recovery counts.
|
||||
|
||||
## Actual83Semrush expansion
|
||||
|
||||
The earlier238-URL candidate review had99 unresolved HTML/linked entries. Reconciliation of all83 actual observed URLs adds20 unique unresolved targets:19 new path/query targets and index.shtml#S1. Current total258knownURLs/158nonexcluded;119unresolved targets. These20 are unverified body/epoch/encoded/malformed/fragment leads, not20 recovered articles or proven spam. The published R2 app/export is unchanged. Full83variants and17metadata limits are recorded in semrush/indexed83-reconciliation.json.
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+2318
-1301
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,83 @@
|
||||
Explore
|
||||
Help
|
||||
Sign In
|
||||
huncode
|
||||
/
|
||||
videoreg.ru
|
||||
Watch
|
||||
1
|
||||
Star
|
||||
0
|
||||
Fork
|
||||
0
|
||||
Code
|
||||
Issues
|
||||
Pull Requests
|
||||
Actions
|
||||
Packages
|
||||
Projects
|
||||
Releases
|
||||
Wiki
|
||||
Activity
|
||||
Back to workflow rebuild-v2
|
||||
Record V2 R2 complete crawl, archive evidence and five scoped reviews; retain mandatory recovery blocks
|
||||
#7
|
||||
Summary
|
||||
All jobs
|
||||
candidate
|
||||
3m55s
|
||||
Run Details
|
||||
Workflow file
|
||||
candidate
|
||||
|
||||
Failure
|
||||
|
||||
Set up job
|
||||
5s
|
||||
Run actions/checkout@v4
|
||||
33s
|
||||
Run actions/setup-node@v4
|
||||
42s
|
||||
Run npm ci --no-audit --no-fund
|
||||
27s
|
||||
Types, tests and complete static build
|
||||
10s
|
||||
Install pinned recovery verification dependencies
|
||||
1m56s
|
||||
1
|
||||
Run python3 -m venv .local-run/recovery-env
|
||||
6
|
||||
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/beautifulsoup4/
|
||||
7
|
||||
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/beautifulsoup4/
|
||||
8
|
||||
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/beautifulsoup4/
|
||||
9
|
||||
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/beautifulsoup4/
|
||||
10
|
||||
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/beautifulsoup4/
|
||||
11
|
||||
ERROR: Could not find a version that satisfies the requirement beautifulsoup4==4.15.0 (from versions: none)
|
||||
12
|
||||
ERROR: No matching distribution found for beautifulsoup4==4.15.0
|
||||
13
|
||||
Error: Process completed with exit code 1.
|
||||
Validate complete export and safe preview
|
||||
0s
|
||||
Record verification identity and failures in job log
|
||||
0s
|
||||
Complete job
|
||||
1s
|
||||
Job summaries
|
||||
candidate
|
||||
Vitest Test Report
|
||||
Summary
|
||||
Test Files: ✅ 9 passes · 9 total
|
||||
Test Results: ✅ 21 passes · 21 total
|
||||
Powered by Gitea
|
||||
Version: 28.2.0
|
||||
Page: 4ms Template: 0ms
|
||||
Auto
|
||||
English
|
||||
Licenses
|
||||
API
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"run": 1321,
|
||||
"job": 1519,
|
||||
"url": "https://git.pryanik.synology.me/huncode/videoreg.ru/actions/runs/1321",
|
||||
"commit": "44c579714492f06745eb2be350a4f17b96b08417",
|
||||
"branch": "codex/videoreg-rebuild-v2",
|
||||
"observedAt": "2026-10-26T16:05:11.240350+00:00",
|
||||
"method": "Public Gitea rendered UI, dedicatedChromePlaywrightsession; API unauth401 not used as status proof",
|
||||
"status": "Failure",
|
||||
"typesTestsBuild": "passed",
|
||||
"existingTestsPassed": 21,
|
||||
"failureStep": "Install pinned recovery verification dependencies",
|
||||
"failureReason": "PyPI read timeouts, beautifulsoup4 distribution index unavailable on runner",
|
||||
"fullCrawl": "skipped",
|
||||
"productionDeploy": false,
|
||||
"evidence": "run1321-observed-ui.txt",
|
||||
"evidenceSha256": "a9c3e9cd10461b7319e6528acf0c04fae187923b85dfbfa7a921c6bea2bd09be"
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"sourceCandidateCommit": "4a0d828ef070d305bea57d6a5d16d612fc16a0e2",
|
||||
"evidenceCommitPushed": "44c579714492f06745eb2be350a4f17b96b08417",
|
||||
"branch": "codex/videoreg-rebuild-v2",
|
||||
"remote": "ssh://git@git.pryanik.synology.me:2222/huncode/videoreg.ru.git",
|
||||
"branchPushVerifiedBy": "git ls-remote exact44c579714492f06745eb2be350a4f17b96b08417",
|
||||
"rollbackTag": "videoreg-v1-rejected-20261026",
|
||||
"rollbackTagSha": "056f1a6462d62b28ed693ee4829a5e5a00903202",
|
||||
"beadsDoltPull": "succeeded",
|
||||
"beadsDoltPush": "succeeded",
|
||||
"ciRun1321": "Failure atPyPIdependencyinstall;types21testsbuildPASS;fullcrawlsKIPPED",
|
||||
"ciEvidence": "ci/run1321.json",
|
||||
"productionChanged": false,
|
||||
"nextCommitScope": "83exactURLreconciliation+20unresolvedinventoryleads+boundedrecoverybatch+offlineCIfix; app/exportunchanged",
|
||||
"updatedAt": "2026-10-26T16:06:52.772402+00:00"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{"raw": "raw/first.html", "httpStatus": "429", "bytes": 17, "curlExit": 0, "error": ""}
|
||||
.
|
||||
----------------------------------------------------------------------
|
||||
Ran 1 test in 0.002s
|
||||
|
||||
OK
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+1
@@ -0,0 +1 @@
|
||||
[]
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>Wayback Machine</title>
|
||||
<script>
|
||||
/*
|
||||
@licstart The following is the entire license notice for the JavaScript code in this page.
|
||||
|
||||
Copyright (C) 2020 Internet Archive
|
||||
|
||||
The JavaScript code in this page is free software: you can
|
||||
redistribute it and/or modify it under the terms of the GNU Affero
|
||||
General Public License as published by the Free Software
|
||||
Foundation, either version 3 of the License, or (at your option)
|
||||
any later version. The code is distributed WITHOUT ANY WARRANTY;
|
||||
without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
|
||||
|
||||
As additional permission under GNU AGPL version 3 section 7, you
|
||||
may distribute non-source (e.g., minimized or compacted) forms of
|
||||
that code without the copy of the GNU AGPL normally required by
|
||||
section 4, provided you include this license notice and a URL
|
||||
through which recipients can access the Corresponding Source.
|
||||
|
||||
@licend The above is the entire license notice for the JavaScript code in this page.
|
||||
*/
|
||||
</script> <script type="text/javascript">
|
||||
window.webComponentLoaderConfig = {
|
||||
baseUrl: 'https://archive.org',
|
||||
version: '29e56e87'
|
||||
}
|
||||
</script>
|
||||
<!-- is_embedded: True; context: <wayback.replay.core.ReplayContext object at 0x7fb476b20260> -->
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta http-equiv="content-type" content="text/html; charset=utf-8">
|
||||
<link rel="stylesheet" type="text/css" href="https://web-static.archive.org/_static/css/styles.css?v=Zb1uSJFF" />
|
||||
<script type="text/javascript" src="https://web-static.archive.org/_static/js/ui.js?v=7LYlZ-C2" charset="utf-8"></script>
|
||||
<base target="_top">
|
||||
<link rel="stylesheet" type="text/css" href="https://web-static.archive.org/_static/css/web.css">
|
||||
<script type="text/javascript">
|
||||
if (window!=window.top) {
|
||||
$(document).ready(function(){ document.body.classList.add('wb_embedded') });
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body class="navia wb_embedded">
|
||||
<div class="container">
|
||||
<div class="row" style="margin-top: 30px">
|
||||
<div class="col-md-4 col-sm-4 col-xs-4 text-right">
|
||||
<div id="donation-link" class="web_message">
|
||||
<a href="http://archive.org/donate/?origin=wbwww-CalndrDonateButton" data-event-click-tracking="Wayback|DonateButton" class="beta_button">DONATE</a>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="col-md-4 col-sm-4 col-xs-4 text-center">
|
||||
<div class="search-toolbar-logo-container">
|
||||
<a href="/"><div class="search-toolbar-logo" alt="logo: Internet Archive's Wayback Machine"></div></a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="errorBorder">
|
||||
<div id="positionHome">
|
||||
<div id="searchHome">
|
||||
<form name="form1" method="get" action="/web/submit">
|
||||
<input class="form-control" type="text" name="url" value="http://videoreg.ru/shop/index.php?productID=138" size="40" onfocus="javascript:this.focus();this.select();" >
|
||||
<button class="btn btn-default" type="submit" name="type" value="replay">Latest</button>
|
||||
<button class="btn btn-default" type="submit" name="type" value="urlquery">Show All</button>
|
||||
</form>
|
||||
</div>
|
||||
<div id="error">
|
||||
<div class="error-text">The Wayback Machine has not archived that URL.</div>
|
||||
<div class="error-help error-help-proceed">
|
||||
<p>Click here to search for all archived pages under
|
||||
<a href="https://web.archive.org/web/*/http://videoreg.ru/shop/*">http://videoreg.ru/shop/</a>.
|
||||
</p>
|
||||
</div></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<noscript>
|
||||
<div class="no-script-message">
|
||||
The Wayback Machine requires your browser to support JavaScript, please email <a href="mailto:info@archive.org">info@archive.org</a><br/>if you have any questions about this.
|
||||
</div>
|
||||
</noscript>
|
||||
<footer>
|
||||
<div id="footerHome">
|
||||
<p>
|
||||
The Wayback Machine is an initiative of the
|
||||
<a href="//archive.org/">Internet Archive</a>,
|
||||
a 501(c)(3) non-profit, building a digital library of
|
||||
Internet sites and other cultural artifacts in digital form.
|
||||
<br/>Other <a href="//archive.org/projects/">projects</a> include
|
||||
<a href="https://openlibrary.org/">Open Library</a> &
|
||||
<a href="https://archive-it.org">archive-it.org</a>.
|
||||
</p>
|
||||
<p>
|
||||
Your use of the Wayback Machine is subject to the Internet Archive's
|
||||
<a href="//archive.org/about/terms.php">Terms of Use</a>.
|
||||
</p>
|
||||
</div>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>Wayback Machine</title>
|
||||
<script>
|
||||
/*
|
||||
@licstart The following is the entire license notice for the JavaScript code in this page.
|
||||
|
||||
Copyright (C) 2020 Internet Archive
|
||||
|
||||
The JavaScript code in this page is free software: you can
|
||||
redistribute it and/or modify it under the terms of the GNU Affero
|
||||
General Public License as published by the Free Software
|
||||
Foundation, either version 3 of the License, or (at your option)
|
||||
any later version. The code is distributed WITHOUT ANY WARRANTY;
|
||||
without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
|
||||
|
||||
As additional permission under GNU AGPL version 3 section 7, you
|
||||
may distribute non-source (e.g., minimized or compacted) forms of
|
||||
that code without the copy of the GNU AGPL normally required by
|
||||
section 4, provided you include this license notice and a URL
|
||||
through which recipients can access the Corresponding Source.
|
||||
|
||||
@licend The above is the entire license notice for the JavaScript code in this page.
|
||||
*/
|
||||
</script> <script type="text/javascript">
|
||||
window.webComponentLoaderConfig = {
|
||||
baseUrl: 'https://archive.org',
|
||||
version: '29e56e87'
|
||||
}
|
||||
</script>
|
||||
<!-- is_embedded: True; context: <wayback.replay.core.ReplayContext object at 0x7f8897ac5e50> -->
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta http-equiv="content-type" content="text/html; charset=utf-8">
|
||||
<link rel="stylesheet" type="text/css" href="https://web-static.archive.org/_static/css/styles.css?v=Zb1uSJFF" />
|
||||
<script type="text/javascript" src="https://web-static.archive.org/_static/js/ui.js?v=7LYlZ-C2" charset="utf-8"></script>
|
||||
<base target="_top">
|
||||
<link rel="stylesheet" type="text/css" href="https://web-static.archive.org/_static/css/web.css">
|
||||
<script type="text/javascript">
|
||||
if (window!=window.top) {
|
||||
$(document).ready(function(){ document.body.classList.add('wb_embedded') });
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body class="navia wb_embedded">
|
||||
<div class="container">
|
||||
<div class="row" style="margin-top: 30px">
|
||||
<div class="col-md-4 col-sm-4 col-xs-4 text-right">
|
||||
<div id="donation-link" class="web_message">
|
||||
<a href="http://archive.org/donate/?origin=wbwww-CalndrDonateButton" data-event-click-tracking="Wayback|DonateButton" class="beta_button">DONATE</a>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="col-md-4 col-sm-4 col-xs-4 text-center">
|
||||
<div class="search-toolbar-logo-container">
|
||||
<a href="/"><div class="search-toolbar-logo" alt="logo: Internet Archive's Wayback Machine"></div></a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="errorBorder">
|
||||
<div id="positionHome">
|
||||
<div id="searchHome">
|
||||
<form name="form1" method="get" action="/web/submit">
|
||||
<input class="form-control" type="text" name="url" value="http://www.videoreg.ru/shop/index.php?productID=138" size="40" onfocus="javascript:this.focus();this.select();" >
|
||||
<button class="btn btn-default" type="submit" name="type" value="replay">Latest</button>
|
||||
<button class="btn btn-default" type="submit" name="type" value="urlquery">Show All</button>
|
||||
</form>
|
||||
</div>
|
||||
<div id="error">
|
||||
<div class="error-text">The Wayback Machine has not archived that URL.</div>
|
||||
<div class="error-help error-help-proceed">
|
||||
<p>Click here to search for all archived pages under
|
||||
<a href="https://web.archive.org/web/*/http://www.videoreg.ru/shop/*">http://www.videoreg.ru/shop/</a>.
|
||||
</p>
|
||||
</div></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<noscript>
|
||||
<div class="no-script-message">
|
||||
The Wayback Machine requires your browser to support JavaScript, please email <a href="mailto:info@archive.org">info@archive.org</a><br/>if you have any questions about this.
|
||||
</div>
|
||||
</noscript>
|
||||
<footer>
|
||||
<div id="footerHome">
|
||||
<p>
|
||||
The Wayback Machine is an initiative of the
|
||||
<a href="//archive.org/">Internet Archive</a>,
|
||||
a 501(c)(3) non-profit, building a digital library of
|
||||
Internet sites and other cultural artifacts in digital form.
|
||||
<br/>Other <a href="//archive.org/projects/">projects</a> include
|
||||
<a href="https://openlibrary.org/">Open Library</a> &
|
||||
<a href="https://archive-it.org">archive-it.org</a>.
|
||||
</p>
|
||||
<p>
|
||||
Your use of the Wayback Machine is subject to the Internet Archive's
|
||||
<a href="//archive.org/about/terms.php">Terms of Use</a>.
|
||||
</p>
|
||||
</div>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,103 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>Wayback Machine</title>
|
||||
<script>
|
||||
/*
|
||||
@licstart The following is the entire license notice for the JavaScript code in this page.
|
||||
|
||||
Copyright (C) 2020 Internet Archive
|
||||
|
||||
The JavaScript code in this page is free software: you can
|
||||
redistribute it and/or modify it under the terms of the GNU Affero
|
||||
General Public License as published by the Free Software
|
||||
Foundation, either version 3 of the License, or (at your option)
|
||||
any later version. The code is distributed WITHOUT ANY WARRANTY;
|
||||
without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
|
||||
|
||||
As additional permission under GNU AGPL version 3 section 7, you
|
||||
may distribute non-source (e.g., minimized or compacted) forms of
|
||||
that code without the copy of the GNU AGPL normally required by
|
||||
section 4, provided you include this license notice and a URL
|
||||
through which recipients can access the Corresponding Source.
|
||||
|
||||
@licend The above is the entire license notice for the JavaScript code in this page.
|
||||
*/
|
||||
</script> <script type="text/javascript">
|
||||
window.webComponentLoaderConfig = {
|
||||
baseUrl: 'https://archive.org',
|
||||
version: '29e56e87'
|
||||
}
|
||||
</script>
|
||||
<!-- is_embedded: True; context: <wayback.replay.core.ReplayContext object at 0x7f8897ac5e50> -->
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta http-equiv="content-type" content="text/html; charset=utf-8">
|
||||
<link rel="stylesheet" type="text/css" href="https://web-static.archive.org/_static/css/styles.css?v=Zb1uSJFF" />
|
||||
<script type="text/javascript" src="https://web-static.archive.org/_static/js/ui.js?v=7LYlZ-C2" charset="utf-8"></script>
|
||||
<base target="_top">
|
||||
<link rel="stylesheet" type="text/css" href="https://web-static.archive.org/_static/css/web.css">
|
||||
<script type="text/javascript">
|
||||
if (window!=window.top) {
|
||||
$(document).ready(function(){ document.body.classList.add('wb_embedded') });
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body class="navia wb_embedded">
|
||||
<div class="container">
|
||||
<div class="row" style="margin-top: 30px">
|
||||
<div class="col-md-4 col-sm-4 col-xs-4 text-right">
|
||||
<div id="donation-link" class="web_message">
|
||||
<a href="http://archive.org/donate/?origin=wbwww-CalndrDonateButton" data-event-click-tracking="Wayback|DonateButton" class="beta_button">DONATE</a>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="col-md-4 col-sm-4 col-xs-4 text-center">
|
||||
<div class="search-toolbar-logo-container">
|
||||
<a href="/"><div class="search-toolbar-logo" alt="logo: Internet Archive's Wayback Machine"></div></a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="errorBorder">
|
||||
<div id="positionHome">
|
||||
<div id="searchHome">
|
||||
<form name="form1" method="get" action="/web/submit">
|
||||
<input class="form-control" type="text" name="url" value="http://www.videoreg.ru/shop/index.php?productID=138" size="40" onfocus="javascript:this.focus();this.select();" >
|
||||
<button class="btn btn-default" type="submit" name="type" value="replay">Latest</button>
|
||||
<button class="btn btn-default" type="submit" name="type" value="urlquery">Show All</button>
|
||||
</form>
|
||||
</div>
|
||||
<div id="error">
|
||||
<div class="error-text">The Wayback Machine has not archived that URL.</div>
|
||||
<div class="error-help error-help-proceed">
|
||||
<p>Click here to search for all archived pages under
|
||||
<a href="https://web.archive.org/web/*/http://www.videoreg.ru/shop/*">http://www.videoreg.ru/shop/</a>.
|
||||
</p>
|
||||
</div></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<noscript>
|
||||
<div class="no-script-message">
|
||||
The Wayback Machine requires your browser to support JavaScript, please email <a href="mailto:info@archive.org">info@archive.org</a><br/>if you have any questions about this.
|
||||
</div>
|
||||
</noscript>
|
||||
<footer>
|
||||
<div id="footerHome">
|
||||
<p>
|
||||
The Wayback Machine is an initiative of the
|
||||
<a href="//archive.org/">Internet Archive</a>,
|
||||
a 501(c)(3) non-profit, building a digital library of
|
||||
Internet sites and other cultural artifacts in digital form.
|
||||
<br/>Other <a href="//archive.org/projects/">projects</a> include
|
||||
<a href="https://openlibrary.org/">Open Library</a> &
|
||||
<a href="https://archive-it.org">archive-it.org</a>.
|
||||
</p>
|
||||
<p>
|
||||
Your use of the Wayback Machine is subject to the Internet Archive's
|
||||
<a href="//archive.org/about/terms.php">Terms of Use</a>.
|
||||
</p>
|
||||
</div>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,20 @@
|
||||
HTTP/2 404
|
||||
server: nginx
|
||||
date: Mon, 26 Oct 2026 15:55:51 GMT
|
||||
content-type: text/html
|
||||
server-timing: captures_list;dur=0.627643, exclusion.robots;dur=0.052118, exclusion.robots.policy;dur=0.037271, esindex;dur=0.011114, cdx.remote;dur=32.669239, LoadShardBlock;dur=398.453648, PetaboxLoader3.datanode;dur=34.539082, PetaboxLoader3.resolve;dur=290.360501
|
||||
x-app-server: wwwb-app222-dc8
|
||||
x-ts: 404
|
||||
x-tr: 449
|
||||
server-timing: TR;dur=0,Tw;dur=0,Tc;dur=0
|
||||
x-location: All
|
||||
x-as: 13238
|
||||
x-rl: 0
|
||||
x-na: 0
|
||||
x-page-cache: MISS
|
||||
x-nid: YANDEX LLC
|
||||
referrer-policy: no-referrer-when-downgrade
|
||||
permissions-policy: interest-cohort=()
|
||||
x-sd: 0
|
||||
content-encoding: gzip
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>Wayback Machine</title>
|
||||
<script>
|
||||
/*
|
||||
@licstart The following is the entire license notice for the JavaScript code in this page.
|
||||
|
||||
Copyright (C) 2020 Internet Archive
|
||||
|
||||
The JavaScript code in this page is free software: you can
|
||||
redistribute it and/or modify it under the terms of the GNU Affero
|
||||
General Public License as published by the Free Software
|
||||
Foundation, either version 3 of the License, or (at your option)
|
||||
any later version. The code is distributed WITHOUT ANY WARRANTY;
|
||||
without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
|
||||
|
||||
As additional permission under GNU AGPL version 3 section 7, you
|
||||
may distribute non-source (e.g., minimized or compacted) forms of
|
||||
that code without the copy of the GNU AGPL normally required by
|
||||
section 4, provided you include this license notice and a URL
|
||||
through which recipients can access the Corresponding Source.
|
||||
|
||||
@licend The above is the entire license notice for the JavaScript code in this page.
|
||||
*/
|
||||
</script> <script type="text/javascript">
|
||||
window.webComponentLoaderConfig = {
|
||||
baseUrl: 'https://archive.org',
|
||||
version: '29e56e87'
|
||||
}
|
||||
</script>
|
||||
<!-- is_embedded: True; context: <wayback.replay.core.ReplayContext object at 0x7fb476b20260> -->
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta http-equiv="content-type" content="text/html; charset=utf-8">
|
||||
<link rel="stylesheet" type="text/css" href="https://web-static.archive.org/_static/css/styles.css?v=Zb1uSJFF" />
|
||||
<script type="text/javascript" src="https://web-static.archive.org/_static/js/ui.js?v=7LYlZ-C2" charset="utf-8"></script>
|
||||
<base target="_top">
|
||||
<link rel="stylesheet" type="text/css" href="https://web-static.archive.org/_static/css/web.css">
|
||||
<script type="text/javascript">
|
||||
if (window!=window.top) {
|
||||
$(document).ready(function(){ document.body.classList.add('wb_embedded') });
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body class="navia wb_embedded">
|
||||
<div class="container">
|
||||
<div class="row" style="margin-top: 30px">
|
||||
<div class="col-md-4 col-sm-4 col-xs-4 text-right">
|
||||
<div id="donation-link" class="web_message">
|
||||
<a href="http://archive.org/donate/?origin=wbwww-CalndrDonateButton" data-event-click-tracking="Wayback|DonateButton" class="beta_button">DONATE</a>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="col-md-4 col-sm-4 col-xs-4 text-center">
|
||||
<div class="search-toolbar-logo-container">
|
||||
<a href="/"><div class="search-toolbar-logo" alt="logo: Internet Archive's Wayback Machine"></div></a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="errorBorder">
|
||||
<div id="positionHome">
|
||||
<div id="searchHome">
|
||||
<form name="form1" method="get" action="/web/submit">
|
||||
<input class="form-control" type="text" name="url" value="http://videoreg.ru/shop/index.php?productID=138" size="40" onfocus="javascript:this.focus();this.select();" >
|
||||
<button class="btn btn-default" type="submit" name="type" value="replay">Latest</button>
|
||||
<button class="btn btn-default" type="submit" name="type" value="urlquery">Show All</button>
|
||||
</form>
|
||||
</div>
|
||||
<div id="error">
|
||||
<div class="error-text">The Wayback Machine has not archived that URL.</div>
|
||||
<div class="error-help error-help-proceed">
|
||||
<p>Click here to search for all archived pages under
|
||||
<a href="https://web.archive.org/web/*/http://videoreg.ru/shop/*">http://videoreg.ru/shop/</a>.
|
||||
</p>
|
||||
</div></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<noscript>
|
||||
<div class="no-script-message">
|
||||
The Wayback Machine requires your browser to support JavaScript, please email <a href="mailto:info@archive.org">info@archive.org</a><br/>if you have any questions about this.
|
||||
</div>
|
||||
</noscript>
|
||||
<footer>
|
||||
<div id="footerHome">
|
||||
<p>
|
||||
The Wayback Machine is an initiative of the
|
||||
<a href="//archive.org/">Internet Archive</a>,
|
||||
a 501(c)(3) non-profit, building a digital library of
|
||||
Internet sites and other cultural artifacts in digital form.
|
||||
<br/>Other <a href="//archive.org/projects/">projects</a> include
|
||||
<a href="https://openlibrary.org/">Open Library</a> &
|
||||
<a href="https://archive-it.org">archive-it.org</a>.
|
||||
</p>
|
||||
<p>
|
||||
Your use of the Wayback Machine is subject to the Internet Archive's
|
||||
<a href="//archive.org/about/terms.php">Terms of Use</a>.
|
||||
</p>
|
||||
</div>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,20 @@
|
||||
HTTP/2 404
|
||||
server: nginx
|
||||
date: Mon, 26 Oct 2026 15:55:53 GMT
|
||||
content-type: text/html
|
||||
server-timing: captures_list;dur=0.419593, exclusion.robots;dur=0.041324, exclusion.robots.policy;dur=0.032019, esindex;dur=0.007188, cdx.remote;dur=26.807631, LoadShardBlock;dur=110.354290, PetaboxLoader3.datanode;dur=96.406553, PetaboxLoader3.resolve;dur=11.927429
|
||||
x-app-server: wwwb-app218-dc8
|
||||
x-ts: 404
|
||||
x-tr: 154
|
||||
server-timing: TR;dur=0,Tw;dur=0,Tc;dur=0
|
||||
x-location: All
|
||||
x-as: 13238
|
||||
x-rl: 0
|
||||
x-na: 0
|
||||
x-page-cache: MISS
|
||||
x-nid: YANDEX LLC
|
||||
referrer-policy: no-referrer-when-downgrade
|
||||
permissions-policy: interest-cohort=()
|
||||
x-sd: 0
|
||||
content-encoding: gzip
|
||||
|
||||
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1 @@
|
||||
[]
|
||||
@@ -0,0 +1,21 @@
|
||||
HTTP/2 200
|
||||
server: nginx
|
||||
date: Mon, 26 Oct 2026 15:55:41 GMT
|
||||
content-type: application/json
|
||||
server-timing: exclusion.robots;dur=0.106032, exclusion.robots.policy;dur=0.091013, esindex;dur=0.007720
|
||||
x-app-server: wwwb-app240-dc6
|
||||
x-ts: 200
|
||||
x-tr: 7964
|
||||
server-timing: TR;dur=0,Tw;dur=0,Tc;dur=1
|
||||
x-location: cdx
|
||||
x-rl: 0
|
||||
x-na: 0
|
||||
x-page-cache: BYPASS
|
||||
server-timing: BYPASS
|
||||
x-nid: YANDEX LLC
|
||||
referrer-policy: no-referrer-when-downgrade
|
||||
permissions-policy: interest-cohort=()
|
||||
x-sd: 0
|
||||
x-be: wb_cdx_pygwb_nomatch
|
||||
content-encoding: gzip
|
||||
|
||||
@@ -947,3 +947,10 @@
|
||||
{"url": "https://web.archive.org/web/20090205154916id_/http://videoreg.ru:80/download/svk-002-mn.pdf", "raw": "docs/rebuild-v2/raw/svk002-review-exact.pdf", "immutableRaw": "docs/rebuild-v2/raw/objects/a7c4a9b8788b0632610f2dc41020928e5a856d3bd2ff7f9ad29d51cdeec36e94.bin", "sha256": "a7c4a9b8788b0632610f2dc41020928e5a856d3bd2ff7f9ad29d51cdeec36e94", "bytes": 244198, "httpStatus": "200", "effectiveUrl": "https://web.archive.org/web/20090205154916id_/http://videoreg.ru:80/download/svk-002-mn.pdf", "curlExit": 28, "error": "curl: (28) Operation timed out after 40005 milliseconds with 244198 out of 872857 bytes received", "checkedAt": "2026-10-26T15:04:48Z", "seconds": 40.02}
|
||||
{"url": "https://web.archive.org/web/20090205154916id_/http://videoreg.ru:80/download/svk-002-mn.pdf", "raw": "docs/rebuild-v2/raw/svk002-review-complete.pdf", "immutableRaw": "docs/rebuild-v2/raw/objects/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.bin", "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "bytes": 0, "httpStatus": "000", "effectiveUrl": "https://web.archive.org/web/20090205154916id_/http://videoreg.ru:80/download/svk-002-mn.pdf", "curlExit": 7, "error": "curl: (7) Failed to connect to web.archive.org port 443 after 280 ms: Couldn't connect to server", "checkedAt": "2026-10-26T15:05:06Z", "seconds": 0.29}
|
||||
{"url": "https://web.archive.org/web/2009id_/http://videoreg.ru:80/download/svk-002-mn.pdf", "raw": "docs/rebuild-v2/raw/svk002-review-retry-0.bin", "immutableRaw": "docs/rebuild-v2/raw/objects/1e2eb3055318622a154c1ca3780a4de4e85caf1df71e81669153daa5cde3cf2b.bin", "sha256": "1e2eb3055318622a154c1ca3780a4de4e85caf1df71e81669153daa5cde3cf2b", "bytes": 872857, "httpStatus": "200", "effectiveUrl": "https://web.archive.org/web/20090205154916id_/http://videoreg.ru/download/svk-002-mn.pdf", "curlExit": 0, "error": "", "checkedAt": "2026-10-26T15:06:51Z", "seconds": 90.14}
|
||||
{"url": "https://web.archive.org/cdx/search/cdx?url=http%3A%2F%2Fwww.videoreg.ru%2Fforum%2Fviewtopic.php%3Ft%3D196&output=json&collapse=digest&filter=statuscode%3A200&fl=timestamp%2Coriginal%2Cmimetype%2Cstatuscode%2Cdigest%2Clength", "raw": "docs/rebuild-v2/raw/priority83-topic196-cdx.json", "immutableRaw": "docs/rebuild-v2/raw/objects/37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570.bin", "sha256": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", "bytes": 3, "httpStatus": "200", "effectiveUrl": "https://web.archive.org/cdx/search/cdx?url=http%3A%2F%2Fwww.videoreg.ru%2Fforum%2Fviewtopic.php%3Ft%3D196&output=json&collapse=digest&filter=statuscode%3A200&fl=timestamp%2Coriginal%2Cmimetype%2Cstatuscode%2Cdigest%2Clength", "curlExit": 0, "error": "", "checkedAt": "2026-10-26T15:55:41Z", "seconds": 11.24}
|
||||
{"url": "https://web.archive.org/cdx/search/cdx?url=http%3A%2F%2Fwww.videoreg.ru%2Fshop%2Findex.php%3FproductID%3D138&output=json&collapse=digest&filter=statuscode%3A200&fl=timestamp%2Coriginal%2Cmimetype%2Cstatuscode%2Cdigest%2Clength", "raw": "docs/rebuild-v2/raw/priority83-product138-cdx.json", "immutableRaw": "docs/rebuild-v2/raw/objects/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.bin", "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "bytes": 0, "httpStatus": "000", "effectiveUrl": "https://web.archive.org/cdx/search/cdx?url=http%3A%2F%2Fwww.videoreg.ru%2Fshop%2Findex.php%3FproductID%3D138&output=json&collapse=digest&filter=statuscode%3A200&fl=timestamp%2Coriginal%2Cmimetype%2Cstatuscode%2Cdigest%2Clength", "curlExit": 7, "error": "curl: (7) Failed to connect to web.archive.org port 443 after 213 ms: Couldn't connect to server", "checkedAt": "2026-10-26T15:55:43Z", "seconds": 0.24}
|
||||
{"url": "https://web.archive.org/web/2012id_/http://www.videoreg.ru:80/forum/viewtopic.php?t=196", "raw": "docs/rebuild-v2/raw/priority83-topic196-0.bin", "immutableRaw": "docs/rebuild-v2/raw/objects/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.bin", "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "bytes": 0, "httpStatus": "000", "effectiveUrl": "https://web.archive.org/web/2012id_/http://www.videoreg.ru:80/forum/viewtopic.php?t=196", "curlExit": 7, "error": "curl: (7) Failed to connect to web.archive.org port 443 after 211 ms: Couldn't connect to server", "checkedAt": "2026-10-26T15:55:45Z", "seconds": 0.22}
|
||||
{"url": "https://web.archive.org/web/2009id_/http://videoreg.ru:80/forum/viewtopic.php?t=196", "raw": "docs/rebuild-v2/raw/priority83-topic196-1.bin", "immutableRaw": "docs/rebuild-v2/raw/objects/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.bin", "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "bytes": 0, "httpStatus": "000", "effectiveUrl": "https://web.archive.org/web/2009id_/http://videoreg.ru:80/forum/viewtopic.php?t=196", "curlExit": 7, "error": "curl: (7) Failed to connect to web.archive.org port 443 after 213 ms: Couldn't connect to server", "checkedAt": "2026-10-26T15:55:48Z", "seconds": 0.23}
|
||||
{"url": "https://web.archive.org/web/2009id_/http://www.videoreg.ru:80/shop/index.php?productID=138", "raw": "docs/rebuild-v2/raw/priority83-product138-0.bin", "immutableRaw": "docs/rebuild-v2/raw/objects/95b32c27a1fce5b9014defda949d77068a038e114cd1587820a501fd85112960.bin", "sha256": "95b32c27a1fce5b9014defda949d77068a038e114cd1587820a501fd85112960", "bytes": 4622, "httpStatus": "404", "effectiveUrl": "https://web.archive.org/web/2009id_/http://www.videoreg.ru:80/shop/index.php?productID=138", "curlExit": 0, "error": "", "checkedAt": "2026-10-26T15:55:51Z", "seconds": 1.08}
|
||||
{"url": "https://web.archive.org/web/2012id_/http://videoreg.ru:80/shop/index.php?productID=138", "raw": "docs/rebuild-v2/raw/priority83-product138-1.bin", "immutableRaw": "docs/rebuild-v2/raw/objects/3f1b9c004d86ed197d4b49e1fe168bcbf707a15d3e252dd77a34f88ec5dcb5d2.bin", "sha256": "3f1b9c004d86ed197d4b49e1fe168bcbf707a15d3e252dd77a34f88ec5dcb5d2", "bytes": 4610, "httpStatus": "404", "effectiveUrl": "https://web.archive.org/web/2012id_/http://videoreg.ru:80/shop/index.php?productID=138", "curlExit": 0, "error": "", "checkedAt": "2026-10-26T15:55:54Z", "seconds": 0.81}
|
||||
{"url": "https://web.archive.org/web/20160914115702id_/http://videoreg.ru/download/doc/svk-007-instr.zip", "raw": "docs/rebuild-v2/raw/priority83-svk007-hyphen-zip-0.bin", "immutableRaw": "docs/rebuild-v2/raw/objects/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.bin", "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "bytes": 0, "httpStatus": "000", "effectiveUrl": "https://web.archive.org/web/20160914115702id_/http://videoreg.ru/download/doc/svk-007-instr.zip", "curlExit": 7, "error": "curl: (7) Failed to connect to web.archive.org port 443 after 204 ms: Couldn't connect to server", "checkedAt": "2026-10-26T15:55:56Z", "seconds": 0.22}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,19 @@
|
||||
# Сверка 83 наблюдавшихся URL Semrush
|
||||
|
||||
Получен точный URL-only transcript координатора; сохранён без изменений как `observed-indexed-all83-urls.json`, SHA256 `46f725474439733eb0619b846ee67355e97bd16fb1b6b9fd1540a15817dc28d7`. Это наблюдение DOM ранее открытого авторизованного отчёта, не новая выгрузка CSV и не самостоятельная проверка UI этим рецензентом.
|
||||
|
||||
`indexed83-reconciliation.json` содержит **83 отдельные строки в исходном порядке**. В каждой сохранены полный URL и исходные scheme/www/query/fragment; соответствие историческому пути отдельно от точного original URL. Значения метаданных приложены только к17 точным URL из прежнего transcript. Остальные66 URL не получили придуманных счётчиков/названий/дат. В отчёте заявлено89 строк: шесть ненаблюдавшихся URL по-прежнему неизвестны. Прежние файлы с17 строками оставлены как самостоятельное историческое свидетельство, их старый scope не переписан.
|
||||
|
||||
44 URL имеют соответствующий путь/запрос с ранее валидированным историческим телом; это не доказательство тела на точном scheme/www или в момент индексирования. Ещё один URL — `index.shtml#S1`: историческая родительская страница известна, но S1 id/name в сохранённом теле не найден, назначение фрагмента не объявлено восстановленным.32 URL отсутствуют в инвентаре без дополнительных специальных признаков: в том числе профили/аккаунты/конкурсы и похожие поздние пути. Их эпоха и содержание **body-unverified/unknown**; URL или заголовок не доказывают Blox, спам, expiry или допустимость исключения.
|
||||
|
||||
Отдельно отмечены два варианта `categoryID=79%29`, один encoded camera path, один profile u4993, product133 и нерешённые product138/topic196. `%29` не удалён и не приравнен к известной категории79. Product133 уже имеет исторический raw и не требует повторной загрузки только из-за www-варианта. Для138 и196 прочитаны сохранённые попытки: это Wayback wrapper с HTTP404, **не тела продукта/темы**.
|
||||
|
||||
Следующий небольшой приоритетный пакет для root при отсутствии действующей паузы429 (локальный requests ledger на момент пакета не содержит429; при первом429 все Wayback-запросы на этом IP прекращаются):
|
||||
|
||||
1. `http://videoreg.ru/shop/index.php?productID=138` — самостоятельный продукт; не смешивать с133/132.
|
||||
2. `http://www.videoreg.ru/forum/viewtopic.php?t=196` — самостоятельная тема; старый apex2008 дал404, www-попытки завершались сетевой ошибкой.
|
||||
3. `http://videoreg.ru/logitech%20quickcam%20for%20notebooks%20deluxe` — новый camera-specific path, содержание неизвестно.
|
||||
4. `http://videoreg.ru/shop/index.php?categoryID=79%29` и точный HTTPS-вариант — malformed query проверить ограниченно, без автоматического исправления79.
|
||||
5. `http://www.videoreg.ru/forum/profile.php?mode=viewprofile&u=4993` — ниже приоритет содержательных тем; сначала тело/эпоха, без исключения по форме URL.
|
||||
|
||||
Этот проход использовал только существующие локальные файлы, без Wayback/других сетевых запросов. App/build, исходный url-inventory и основной editorial-ledger не изменены. Новых восстановленных тел **0**. `videoreg-7oy.7` остаётся обязательным partial scope:83/89 URL,17/83 metadata, а полнота anchors/referrer-контекстов и фактическое восстановление тел этим не обеспечены. Общего PASS нет.
|
||||
@@ -0,0 +1,96 @@
|
||||
{
|
||||
"source": "Root cached authenticated Semrush IndexedPages DOM observation2026-10-26, exactURL-onlytranscript;notnewqueryorCSVexport",
|
||||
"reportURL": "https://1.semrush.com.in/analytics/backlinks/pages/?q=videoreg.ru&searchType=domain",
|
||||
"reported": 89,
|
||||
"actualObservedRows": 83,
|
||||
"urlsInObservedOrder": [
|
||||
"https://videoreg.ru/",
|
||||
"http://videoreg.ru/",
|
||||
"http://www.videoreg.ru/",
|
||||
"http://www.videoreg.ru/auto.shtml",
|
||||
"http://videoreg.ru/auto.shtml",
|
||||
"http://videoreg.ru/index.shtml",
|
||||
"http://www.videoreg.ru/price.shtml",
|
||||
"http://www.videoreg.ru/support.shtml",
|
||||
"http://www.videoreg.ru/samples.shtml",
|
||||
"http://www.videoreg.ru/shop/index.php?categoryID=78",
|
||||
"http://videoreg.ru/price.shtml",
|
||||
"http://www.videoreg.ru/index.shtml",
|
||||
"http://videoreg.ru/samples.shtml",
|
||||
"http://videoreg.ru/support.shtml",
|
||||
"http://www.videoreg.ru/predpr.shtml",
|
||||
"http://www.videoreg.ru/sert.html",
|
||||
"http://www.videoreg.ru/shop/index.php?aux_page=aux2",
|
||||
"http://videoreg.ru/autopredpr.shtml",
|
||||
"http://videoreg.ru/demo.shtml",
|
||||
"http://videoreg.ru/down.shtml",
|
||||
"http://videoreg.ru/faq.shtml",
|
||||
"http://videoreg.ru/index.shtml#S1",
|
||||
"http://videoreg.ru/logitech%20quickcam%20for%20notebooks%20deluxe",
|
||||
"http://videoreg.ru/moves.htm",
|
||||
"http://videoreg.ru/predpr.shtml",
|
||||
"http://videoreg.ru/sert.html",
|
||||
"http://videoreg.ru/shop/index.php?categoryID=79%29",
|
||||
"http://videoreg.ru/shop/index.php?productID=138",
|
||||
"http://videoreg.ru/where.shtml",
|
||||
"http://www.videoreg.ru/autopredpr.shtml",
|
||||
"http://www.videoreg.ru/demo.shtml",
|
||||
"http://www.videoreg.ru/down.shtml",
|
||||
"http://www.videoreg.ru/faq.shtml",
|
||||
"http://www.videoreg.ru/forum/profile.php?mode=viewprofile&u=4993",
|
||||
"http://www.videoreg.ru/forum/viewforum.php?f=1",
|
||||
"http://www.videoreg.ru/forum/viewtopic.php?t=196",
|
||||
"http://www.videoreg.ru/moves.htm",
|
||||
"http://www.videoreg.ru/shop/index.php",
|
||||
"http://www.videoreg.ru/shop/index.php?productID=133",
|
||||
"http://www.videoreg.ru/where.shtml",
|
||||
"https://videoreg.ru/account",
|
||||
"https://videoreg.ru/account/referrals",
|
||||
"https://videoreg.ru/auto.shtml",
|
||||
"https://videoreg.ru/competition/tiktok",
|
||||
"https://videoreg.ru/competition/youtube",
|
||||
"https://videoreg.ru/dashboard2",
|
||||
"https://videoreg.ru/enter",
|
||||
"https://videoreg.ru/eula",
|
||||
"https://videoreg.ru/forgot",
|
||||
"https://videoreg.ru/giveaway",
|
||||
"https://videoreg.ru/index.shtml",
|
||||
"https://videoreg.ru/join",
|
||||
"https://videoreg.ru/login",
|
||||
"https://videoreg.ru/price.shtml",
|
||||
"https://videoreg.ru/privacy-policy",
|
||||
"https://videoreg.ru/promos",
|
||||
"https://videoreg.ru/return-policy",
|
||||
"https://videoreg.ru/shop/index.php?categoryID=79%29",
|
||||
"https://videoreg.ru/support.shtml",
|
||||
"https://videoreg.ru/terms",
|
||||
"https://videoreg.ru/withdraw",
|
||||
"https://www.videoreg.ru/",
|
||||
"https://www.videoreg.ru/account",
|
||||
"https://www.videoreg.ru/account/referrals",
|
||||
"https://www.videoreg.ru/auto.shtml",
|
||||
"https://www.videoreg.ru/competition/tiktok",
|
||||
"https://www.videoreg.ru/competition/youtube",
|
||||
"https://www.videoreg.ru/dashboard2",
|
||||
"https://www.videoreg.ru/enter",
|
||||
"https://www.videoreg.ru/eula",
|
||||
"https://www.videoreg.ru/giveaway",
|
||||
"https://www.videoreg.ru/join",
|
||||
"https://www.videoreg.ru/login",
|
||||
"https://www.videoreg.ru/predpr.shtml",
|
||||
"https://www.videoreg.ru/price.shtml",
|
||||
"https://www.videoreg.ru/privacy-policy",
|
||||
"https://www.videoreg.ru/promos",
|
||||
"https://www.videoreg.ru/return-policy",
|
||||
"https://www.videoreg.ru/sert.html",
|
||||
"https://www.videoreg.ru/shop/index.php?aux_page=aux2",
|
||||
"https://www.videoreg.ru/shop/index.php?categoryID=78",
|
||||
"https://www.videoreg.ru/terms",
|
||||
"https://www.videoreg.ru/withdraw"
|
||||
],
|
||||
"limitations": [
|
||||
"Sixreportedrowsnotreturned/notinvented.",
|
||||
"Metadataforonlysubsetinseparatefiles.",
|
||||
"URLaloneisnotbodyrestorationorepochproof."
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
{
|
||||
"scope": "3actualcontent/documenttargets; no bulkuniformretry",
|
||||
"leads": [
|
||||
{
|
||||
"key": "topic196",
|
||||
"url": "http://www.videoreg.ru/forum/viewtopic.php?t=196",
|
||||
"title": "Применение доказательств",
|
||||
"why": "Exact Semrush83 target; actual recovered forumf2 listing supplies same technical/legal topic title, no body invented.",
|
||||
"replays": [
|
||||
"https://web.archive.org/web/2012id_/http://www.videoreg.ru:80/forum/viewtopic.php?t=196",
|
||||
"https://web.archive.org/web/2009id_/http://videoreg.ru:80/forum/viewtopic.php?t=196"
|
||||
],
|
||||
"attempts": [
|
||||
{
|
||||
"url": "https://web.archive.org/web/2012id_/http://www.videoreg.ru:80/forum/viewtopic.php?t=196",
|
||||
"raw": "docs/rebuild-v2/raw/priority83-topic196-0.bin",
|
||||
"immutableRaw": "docs/rebuild-v2/raw/objects/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.bin",
|
||||
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||
"bytes": 0,
|
||||
"httpStatus": "000",
|
||||
"effectiveUrl": "https://web.archive.org/web/2012id_/http://www.videoreg.ru:80/forum/viewtopic.php?t=196",
|
||||
"curlExit": 7,
|
||||
"error": "curl: (7) Failed to connect to web.archive.org port 443 after 211 ms: Couldn't connect to server",
|
||||
"checkedAt": "2026-10-26T15:55:45Z",
|
||||
"seconds": 0.22
|
||||
},
|
||||
{
|
||||
"url": "https://web.archive.org/web/2009id_/http://videoreg.ru:80/forum/viewtopic.php?t=196",
|
||||
"raw": "docs/rebuild-v2/raw/priority83-topic196-1.bin",
|
||||
"immutableRaw": "docs/rebuild-v2/raw/objects/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.bin",
|
||||
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||
"bytes": 0,
|
||||
"httpStatus": "000",
|
||||
"effectiveUrl": "https://web.archive.org/web/2009id_/http://videoreg.ru:80/forum/viewtopic.php?t=196",
|
||||
"curlExit": 7,
|
||||
"error": "curl: (7) Failed to connect to web.archive.org port 443 after 213 ms: Couldn't connect to server",
|
||||
"checkedAt": "2026-10-26T15:55:48Z",
|
||||
"seconds": 0.23
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"key": "product138",
|
||||
"url": "http://www.videoreg.ru/shop/index.php?productID=138",
|
||||
"title": "СВК-005",
|
||||
"why": "Exact Semrush83 target; recovered category79 links this model/card. Category summary does not prove full product body.",
|
||||
"replays": [
|
||||
"https://web.archive.org/web/2009id_/http://www.videoreg.ru:80/shop/index.php?productID=138",
|
||||
"https://web.archive.org/web/2012id_/http://videoreg.ru:80/shop/index.php?productID=138"
|
||||
],
|
||||
"attempts": [
|
||||
{
|
||||
"url": "https://web.archive.org/web/2009id_/http://www.videoreg.ru:80/shop/index.php?productID=138",
|
||||
"raw": "docs/rebuild-v2/raw/priority83-product138-0.bin",
|
||||
"immutableRaw": "docs/rebuild-v2/raw/objects/95b32c27a1fce5b9014defda949d77068a038e114cd1587820a501fd85112960.bin",
|
||||
"sha256": "95b32c27a1fce5b9014defda949d77068a038e114cd1587820a501fd85112960",
|
||||
"bytes": 4622,
|
||||
"httpStatus": "404",
|
||||
"effectiveUrl": "https://web.archive.org/web/2009id_/http://www.videoreg.ru:80/shop/index.php?productID=138",
|
||||
"curlExit": 0,
|
||||
"error": "",
|
||||
"checkedAt": "2026-10-26T15:55:51Z",
|
||||
"seconds": 1.08
|
||||
},
|
||||
{
|
||||
"url": "https://web.archive.org/web/2012id_/http://videoreg.ru:80/shop/index.php?productID=138",
|
||||
"raw": "docs/rebuild-v2/raw/priority83-product138-1.bin",
|
||||
"immutableRaw": "docs/rebuild-v2/raw/objects/3f1b9c004d86ed197d4b49e1fe168bcbf707a15d3e252dd77a34f88ec5dcb5d2.bin",
|
||||
"sha256": "3f1b9c004d86ed197d4b49e1fe168bcbf707a15d3e252dd77a34f88ec5dcb5d2",
|
||||
"bytes": 4610,
|
||||
"httpStatus": "404",
|
||||
"effectiveUrl": "https://web.archive.org/web/2012id_/http://videoreg.ru:80/shop/index.php?productID=138",
|
||||
"curlExit": 0,
|
||||
"error": "",
|
||||
"checkedAt": "2026-10-26T15:55:54Z",
|
||||
"seconds": 0.81
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"key": "svk007-hyphen-zip",
|
||||
"url": "http://videoreg.ru/download/doc/svk-007-instr.zip",
|
||||
"title": "svk-007-instr.zip",
|
||||
"why": "Actual resourceCDX20160914115702 and original document link. Differently named underscore manual is not assumed identical.",
|
||||
"replays": [
|
||||
"https://web.archive.org/web/20160914115702id_/http://videoreg.ru/download/doc/svk-007-instr.zip"
|
||||
],
|
||||
"attempts": [
|
||||
{
|
||||
"url": "https://web.archive.org/web/20160914115702id_/http://videoreg.ru/download/doc/svk-007-instr.zip",
|
||||
"raw": "docs/rebuild-v2/raw/priority83-svk007-hyphen-zip-0.bin",
|
||||
"immutableRaw": "docs/rebuild-v2/raw/objects/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.bin",
|
||||
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||
"bytes": 0,
|
||||
"httpStatus": "000",
|
||||
"effectiveUrl": "https://web.archive.org/web/20160914115702id_/http://videoreg.ru/download/doc/svk-007-instr.zip",
|
||||
"curlExit": 7,
|
||||
"error": "curl: (7) Failed to connect to web.archive.org port 443 after 204 ms: Couldn't connect to server",
|
||||
"checkedAt": "2026-10-26T15:55:56Z",
|
||||
"seconds": 0.22
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"requests": [
|
||||
{
|
||||
"url": "https://web.archive.org/cdx/search/cdx?url=http%3A%2F%2Fwww.videoreg.ru%2Fforum%2Fviewtopic.php%3Ft%3D196&output=json&collapse=digest&filter=statuscode%3A200&fl=timestamp%2Coriginal%2Cmimetype%2Cstatuscode%2Cdigest%2Clength",
|
||||
"raw": "docs/rebuild-v2/raw/priority83-topic196-cdx.json",
|
||||
"immutableRaw": "docs/rebuild-v2/raw/objects/37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570.bin",
|
||||
"sha256": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570",
|
||||
"bytes": 3,
|
||||
"httpStatus": "200",
|
||||
"effectiveUrl": "https://web.archive.org/cdx/search/cdx?url=http%3A%2F%2Fwww.videoreg.ru%2Fforum%2Fviewtopic.php%3Ft%3D196&output=json&collapse=digest&filter=statuscode%3A200&fl=timestamp%2Coriginal%2Cmimetype%2Cstatuscode%2Cdigest%2Clength",
|
||||
"curlExit": 0,
|
||||
"error": "",
|
||||
"checkedAt": "2026-10-26T15:55:41Z",
|
||||
"seconds": 11.24
|
||||
},
|
||||
{
|
||||
"url": "https://web.archive.org/cdx/search/cdx?url=http%3A%2F%2Fwww.videoreg.ru%2Fshop%2Findex.php%3FproductID%3D138&output=json&collapse=digest&filter=statuscode%3A200&fl=timestamp%2Coriginal%2Cmimetype%2Cstatuscode%2Cdigest%2Clength",
|
||||
"raw": "docs/rebuild-v2/raw/priority83-product138-cdx.json",
|
||||
"immutableRaw": "docs/rebuild-v2/raw/objects/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.bin",
|
||||
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||
"bytes": 0,
|
||||
"httpStatus": "000",
|
||||
"effectiveUrl": "https://web.archive.org/cdx/search/cdx?url=http%3A%2F%2Fwww.videoreg.ru%2Fshop%2Findex.php%3FproductID%3D138&output=json&collapse=digest&filter=statuscode%3A200&fl=timestamp%2Coriginal%2Cmimetype%2Cstatuscode%2Cdigest%2Clength",
|
||||
"curlExit": 7,
|
||||
"error": "curl: (7) Failed to connect to web.archive.org port 443 after 213 ms: Couldn't connect to server",
|
||||
"checkedAt": "2026-10-26T15:55:43Z",
|
||||
"seconds": 0.24
|
||||
},
|
||||
{
|
||||
"url": "https://web.archive.org/web/2012id_/http://www.videoreg.ru:80/forum/viewtopic.php?t=196",
|
||||
"raw": "docs/rebuild-v2/raw/priority83-topic196-0.bin",
|
||||
"immutableRaw": "docs/rebuild-v2/raw/objects/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.bin",
|
||||
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||
"bytes": 0,
|
||||
"httpStatus": "000",
|
||||
"effectiveUrl": "https://web.archive.org/web/2012id_/http://www.videoreg.ru:80/forum/viewtopic.php?t=196",
|
||||
"curlExit": 7,
|
||||
"error": "curl: (7) Failed to connect to web.archive.org port 443 after 211 ms: Couldn't connect to server",
|
||||
"checkedAt": "2026-10-26T15:55:45Z",
|
||||
"seconds": 0.22
|
||||
},
|
||||
{
|
||||
"url": "https://web.archive.org/web/2009id_/http://videoreg.ru:80/forum/viewtopic.php?t=196",
|
||||
"raw": "docs/rebuild-v2/raw/priority83-topic196-1.bin",
|
||||
"immutableRaw": "docs/rebuild-v2/raw/objects/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.bin",
|
||||
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||
"bytes": 0,
|
||||
"httpStatus": "000",
|
||||
"effectiveUrl": "https://web.archive.org/web/2009id_/http://videoreg.ru:80/forum/viewtopic.php?t=196",
|
||||
"curlExit": 7,
|
||||
"error": "curl: (7) Failed to connect to web.archive.org port 443 after 213 ms: Couldn't connect to server",
|
||||
"checkedAt": "2026-10-26T15:55:48Z",
|
||||
"seconds": 0.23
|
||||
},
|
||||
{
|
||||
"url": "https://web.archive.org/web/2009id_/http://www.videoreg.ru:80/shop/index.php?productID=138",
|
||||
"raw": "docs/rebuild-v2/raw/priority83-product138-0.bin",
|
||||
"immutableRaw": "docs/rebuild-v2/raw/objects/95b32c27a1fce5b9014defda949d77068a038e114cd1587820a501fd85112960.bin",
|
||||
"sha256": "95b32c27a1fce5b9014defda949d77068a038e114cd1587820a501fd85112960",
|
||||
"bytes": 4622,
|
||||
"httpStatus": "404",
|
||||
"effectiveUrl": "https://web.archive.org/web/2009id_/http://www.videoreg.ru:80/shop/index.php?productID=138",
|
||||
"curlExit": 0,
|
||||
"error": "",
|
||||
"checkedAt": "2026-10-26T15:55:51Z",
|
||||
"seconds": 1.08
|
||||
},
|
||||
{
|
||||
"url": "https://web.archive.org/web/2012id_/http://videoreg.ru:80/shop/index.php?productID=138",
|
||||
"raw": "docs/rebuild-v2/raw/priority83-product138-1.bin",
|
||||
"immutableRaw": "docs/rebuild-v2/raw/objects/3f1b9c004d86ed197d4b49e1fe168bcbf707a15d3e252dd77a34f88ec5dcb5d2.bin",
|
||||
"sha256": "3f1b9c004d86ed197d4b49e1fe168bcbf707a15d3e252dd77a34f88ec5dcb5d2",
|
||||
"bytes": 4610,
|
||||
"httpStatus": "404",
|
||||
"effectiveUrl": "https://web.archive.org/web/2012id_/http://videoreg.ru:80/shop/index.php?productID=138",
|
||||
"curlExit": 0,
|
||||
"error": "",
|
||||
"checkedAt": "2026-10-26T15:55:54Z",
|
||||
"seconds": 0.81
|
||||
},
|
||||
{
|
||||
"url": "https://web.archive.org/web/20160914115702id_/http://videoreg.ru/download/doc/svk-007-instr.zip",
|
||||
"raw": "docs/rebuild-v2/raw/priority83-svk007-hyphen-zip-0.bin",
|
||||
"immutableRaw": "docs/rebuild-v2/raw/objects/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.bin",
|
||||
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||
"bytes": 0,
|
||||
"httpStatus": "000",
|
||||
"effectiveUrl": "https://web.archive.org/web/20160914115702id_/http://videoreg.ru/download/doc/svk-007-instr.zip",
|
||||
"curlExit": 7,
|
||||
"error": "curl: (7) Failed to connect to web.archive.org port 443 after 204 ms: Couldn't connect to server",
|
||||
"checkedAt": "2026-10-26T15:55:56Z",
|
||||
"seconds": 0.22
|
||||
}
|
||||
],
|
||||
"acceptedNewBodies": []
|
||||
}
|
||||
@@ -401,25 +401,33 @@
|
||||
{
|
||||
"url": "http://www.videoreg.ru/account",
|
||||
"title": null,
|
||||
"disposition": "excluded-later-unrelated-Blox-state",
|
||||
"disposition": "unresolved-epoch-body-not-verified",
|
||||
"evidence": "Direct coordinator message2026-10-26; exact per-row metrics/date not supplied"
|
||||
},
|
||||
{
|
||||
"url": "http://www.videoreg.ru/join",
|
||||
"title": null,
|
||||
"disposition": "excluded-later-unrelated-Blox-state",
|
||||
"disposition": "unresolved-epoch-body-not-verified",
|
||||
"evidence": "Direct coordinator message2026-10-26; exact per-row metrics/date not supplied"
|
||||
},
|
||||
{
|
||||
"url": "http://www.videoreg.ru/withdraw",
|
||||
"title": null,
|
||||
"disposition": "excluded-later-unrelated-Blox-state",
|
||||
"disposition": "unresolved-epoch-body-not-verified",
|
||||
"evidence": "Direct coordinator message2026-10-26; exact per-row metrics/date not supplied"
|
||||
}
|
||||
],
|
||||
"remainingRequirements": [
|
||||
"Remaining66observedDOM rows and6unloaded reported rows not provided as full export",
|
||||
"Anchors52DOM/3transcribed; LostVital18DOM/6transcribed.5actualreferrersfetched;3HTTP200,2unavailable. Full rowtranscriptions and remainingreferrers remain mandatory.",
|
||||
"Unresolved target bodies/media must be recovered from actual sources; no text synthesized from anchors"
|
||||
]
|
||||
"SixreportedURLrowsnotobserved; nofabrication",
|
||||
"Metadatafor17only;52Anchorrows/3transcribedand18LostVitalrows/6transcribed remainpartial",
|
||||
"Actualunresolvedbodiesandunknown-epochtargets remainmandatory; no URL/title synthesis"
|
||||
],
|
||||
"urlRowsTranscribed": 83,
|
||||
"metadataRowsTranscribed": 17,
|
||||
"reportedButUnseen": 6,
|
||||
"exactUrlReconciliation": "indexed83-reconciliation.json",
|
||||
"urlTranscriptSha256": "46f725474439733eb0619b846ee67355e97bd16fb1b6b9fd1540a15817dc28d7",
|
||||
"expandedInventoryKnownUrls": 258,
|
||||
"currentUnresolvedTargets": 119,
|
||||
"lateEpochPolicy": "URL-only does not prove Blox/expiry/spam; epoch-unverifiedtargets retainedunresolved."
|
||||
}
|
||||
@@ -6,18 +6,90 @@
|
||||
],
|
||||
"status": "awaiting actual coordinator Noxtools/Semrush evidence; not inspected by domain executor",
|
||||
"missing": [
|
||||
{
|
||||
"path": "/account",
|
||||
"url": "https://videoreg.ru/account",
|
||||
"title": null,
|
||||
"source": [
|
||||
"Semrush actual83URLtranscript; metadata only17rows; reported89/sixunseen"
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/account/referrals",
|
||||
"url": "https://videoreg.ru/account/referrals",
|
||||
"title": null,
|
||||
"source": [
|
||||
"Semrush actual83URLtranscript; metadata only17rows; reported89/sixunseen"
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/competition/tiktok",
|
||||
"url": "https://videoreg.ru/competition/tiktok",
|
||||
"title": null,
|
||||
"source": [
|
||||
"Semrush actual83URLtranscript; metadata only17rows; reported89/sixunseen"
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/competition/youtube",
|
||||
"url": "https://videoreg.ru/competition/youtube",
|
||||
"title": null,
|
||||
"source": [
|
||||
"Semrush actual83URLtranscript; metadata only17rows; reported89/sixunseen"
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/dashboard2",
|
||||
"url": "https://videoreg.ru/dashboard2",
|
||||
"title": null,
|
||||
"source": [
|
||||
"Semrush actual83URLtranscript; metadata only17rows; reported89/sixunseen"
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/dilers.shtml",
|
||||
"url": "http://videoreg.ru:80/dilers.shtml",
|
||||
"title": null,
|
||||
"source": []
|
||||
},
|
||||
{
|
||||
"path": "/enter",
|
||||
"url": "https://videoreg.ru/enter",
|
||||
"title": null,
|
||||
"source": [
|
||||
"Semrush actual83URLtranscript; metadata only17rows; reported89/sixunseen"
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/eula",
|
||||
"url": "https://videoreg.ru/eula",
|
||||
"title": null,
|
||||
"source": [
|
||||
"Semrush actual83URLtranscript; metadata only17rows; reported89/sixunseen"
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/forgot",
|
||||
"url": "https://videoreg.ru/forgot",
|
||||
"title": null,
|
||||
"source": [
|
||||
"Semrush actual83URLtranscript; metadata only17rows; reported89/sixunseen"
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/forum/index.php?c=3",
|
||||
"url": "http://www.videoreg.ru:80/forum/index.php?c=3&sid=60918bfef3c3073e0d62d204467787f8",
|
||||
"title": "www.videoreg.ru :: Главная",
|
||||
"source": []
|
||||
},
|
||||
{
|
||||
"path": "/forum/profile.php?mode=viewprofile&u=4993",
|
||||
"url": "http://www.videoreg.ru/forum/profile.php?mode=viewprofile&u=4993",
|
||||
"title": null,
|
||||
"source": [
|
||||
"Semrush actual83URLtranscript; metadata only17rows; reported89/sixunseen"
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/forum/viewforum.php?f=1",
|
||||
"url": "http://www.videoreg.ru:80/forum/viewforum.php?f=1&sid=60918bfef3c3073e0d62d204467787f8",
|
||||
@@ -592,12 +664,36 @@
|
||||
"title": null,
|
||||
"source": []
|
||||
},
|
||||
{
|
||||
"path": "/giveaway",
|
||||
"url": "https://videoreg.ru/giveaway",
|
||||
"title": null,
|
||||
"source": [
|
||||
"Semrush actual83URLtranscript; metadata only17rows; reported89/sixunseen"
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/home.shtml",
|
||||
"url": "http://www.videoreg.ru:80/home.shtml",
|
||||
"title": null,
|
||||
"source": []
|
||||
},
|
||||
{
|
||||
"path": "/index.shtml#S1",
|
||||
"url": "http://videoreg.ru/index.shtml#S1",
|
||||
"title": null,
|
||||
"source": [
|
||||
"Semrush actual83URLtranscript; metadata only17rows; reported89/sixunseen"
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/join",
|
||||
"url": "https://videoreg.ru/join",
|
||||
"title": null,
|
||||
"source": [
|
||||
"Semrush actual83URLtranscript; metadata only17rows; reported89/sixunseen"
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/law1.htm",
|
||||
"url": "http://videoreg.ru:80/law1.htm",
|
||||
@@ -610,6 +706,38 @@
|
||||
"title": null,
|
||||
"source": []
|
||||
},
|
||||
{
|
||||
"path": "/login",
|
||||
"url": "https://videoreg.ru/login",
|
||||
"title": null,
|
||||
"source": [
|
||||
"Semrush actual83URLtranscript; metadata only17rows; reported89/sixunseen"
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/logitech%20quickcam%20for%20notebooks%20deluxe",
|
||||
"url": "http://videoreg.ru/logitech%20quickcam%20for%20notebooks%20deluxe",
|
||||
"title": null,
|
||||
"source": [
|
||||
"Semrush actual83URLtranscript; metadata only17rows; reported89/sixunseen"
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/privacy-policy",
|
||||
"url": "https://videoreg.ru/privacy-policy",
|
||||
"title": null,
|
||||
"source": [
|
||||
"Semrush actual83URLtranscript; metadata only17rows; reported89/sixunseen"
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/promos",
|
||||
"url": "https://videoreg.ru/promos",
|
||||
"title": null,
|
||||
"source": [
|
||||
"Semrush actual83URLtranscript; metadata only17rows; reported89/sixunseen"
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/rek.shtml",
|
||||
"url": "http://www.videoreg.ru:80/rek.shtml",
|
||||
@@ -622,6 +750,22 @@
|
||||
"title": null,
|
||||
"source": []
|
||||
},
|
||||
{
|
||||
"path": "/return-policy",
|
||||
"url": "https://videoreg.ru/return-policy",
|
||||
"title": null,
|
||||
"source": [
|
||||
"Semrush actual83URLtranscript; metadata only17rows; reported89/sixunseen"
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/shop/index.php?categoryID=79%29",
|
||||
"url": "http://videoreg.ru/shop/index.php?categoryID=79%29",
|
||||
"title": null,
|
||||
"source": [
|
||||
"Semrush actual83URLtranscript; metadata only17rows; reported89/sixunseen"
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/shop/index.php?categoryID=81",
|
||||
"url": "http://videoreg.ru:80/shop/index.php?categoryID=81",
|
||||
@@ -693,6 +837,22 @@
|
||||
"url": "http://videoreg.ru:80/shop/index.php?productID=142",
|
||||
"title": null,
|
||||
"source": []
|
||||
},
|
||||
{
|
||||
"path": "/terms",
|
||||
"url": "https://videoreg.ru/terms",
|
||||
"title": null,
|
||||
"source": [
|
||||
"Semrush actual83URLtranscript; metadata only17rows; reported89/sixunseen"
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/withdraw",
|
||||
"url": "https://videoreg.ru/withdraw",
|
||||
"title": null,
|
||||
"source": [
|
||||
"Semrush actual83URLtranscript; metadata only17rows; reported89/sixunseen"
|
||||
]
|
||||
}
|
||||
],
|
||||
"questions": [
|
||||
|
||||
@@ -5,3 +5,7 @@ Coordinator used the shared built-in browser. Report total89, actualDOM83, suppl
|
||||
`reconciliation.json` maps each supplied target to actual raw body/status. Late expiry and Blox account/join/withdraw states do not replace original technical content. Backlink counts are not recovered text.
|
||||
|
||||
Mandatory issue videoreg-7oy.7 stays open: complete exported row coverage and actual referringURL/anchor contexts are still missing.
|
||||
|
||||
## Updated actual83URL transcript
|
||||
|
||||
The coordinator later supplied every83observed exactURL, preserved in observed-indexed-all83-urls.json and reconciled in indexed83-reconciliation.json. Metadata still17only, sixreportedURLs unseen. Twentynew unique unresolvedtargets expand inventory238→258 and unresolved99→119; no body recovered from the transcript. URL-only late-looking paths are epoch-unverified, not provenBlox/spam. The bounded priority83 recovery batch tried actualtopic196/product138 and a distinct original ZIP: no new validated body/resource, no429 observed.
|
||||
+1064
-21
File diff suppressed because it is too large.
Load diff
@@ -14,6 +14,7 @@ from collections import Counter, defaultdict
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
@@ -22,9 +23,17 @@ from urllib.parse import unquote, urldefrag, urljoin, urlsplit, urlunsplit
|
||||
|
||||
try:
|
||||
from bs4 import BeautifulSoup
|
||||
from PIL import Image
|
||||
except ImportError:
|
||||
raise SystemExit("Use .local-run/recovery-env/bin/python; requirements are pinned in scripts/rebuild-v2/requirements.txt")
|
||||
raise SystemExit("Use the pinned recovery Python, or set PYTHONPATH=scripts/rebuild-v2/vendor for offline verification")
|
||||
|
||||
RASTER_DECODER = os.environ.get("VIDEOREG_RASTER_DECODER", "pillow")
|
||||
if RASTER_DECODER not in ("pillow", "sharp"):
|
||||
raise SystemExit("VIDEOREG_RASTER_DECODER must be pillow or sharp; raster validation cannot be disabled")
|
||||
if RASTER_DECODER == "pillow":
|
||||
try:
|
||||
from PIL import Image, ImageSequence
|
||||
except ImportError:
|
||||
raise SystemExit("Pillow is required for the default local decoder; use explicit VIDEOREG_RASTER_DECODER=sharp in offline CI")
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
INTERNAL_HOSTS = {"videoreg.ru", "www.videoreg.ru"}
|
||||
@@ -286,6 +295,34 @@ def main():
|
||||
inventory = read_json(args.inventory, [])
|
||||
legacy = read_json(ROOT / "deploy/legacy-routes.json", {})
|
||||
errors = [{"kind": "export-file-outside-root", "file": x} for x in unsafe_files]
|
||||
repository_git = subprocess.run(["git", "rev-parse", "HEAD"], cwd=ROOT, capture_output=True, text=True)
|
||||
repository_head = repository_git.stdout.strip()
|
||||
built_health = {}
|
||||
try:
|
||||
built_health_path = confined(out / "health/ready", out)
|
||||
if built_health_path is not None:
|
||||
built_health = read_json(built_health_path, {})
|
||||
except (ValueError, OSError) as exc:
|
||||
errors.append(dict(kind="invalid-built-health-metadata", error=str(exc)))
|
||||
metadata = built_health.get("metadata", {}) if isinstance(built_health, dict) else {}
|
||||
built_revision = metadata.get("commitSha") if isinstance(metadata, dict) else None
|
||||
built_source_files = []
|
||||
built_source_manifest = None
|
||||
if not isinstance(built_revision, str) or not re.fullmatch(r"[0-9a-f]{40}", built_revision):
|
||||
errors.append(dict(kind="missing-built-source-revision", value=built_revision))
|
||||
else:
|
||||
# A later docs/tooling commit is not the source revision of an already
|
||||
# built candidate. Compare actual active sources to that Git snapshot.
|
||||
for source in source_before:
|
||||
result = subprocess.run(["git", "show", built_revision + ":" + source["path"]], cwd=ROOT, capture_output=True)
|
||||
if result.returncode:
|
||||
errors.append(dict(kind="built-source-unavailable-in-git", revision=built_revision, file=source["path"]))
|
||||
else:
|
||||
built_source_files.append(dict(path=source["path"], sha256=sha(result.stdout)))
|
||||
if len(built_source_files) == len(source_before):
|
||||
built_source_manifest = manifest_hash(built_source_files)
|
||||
if built_source_manifest != manifest_hash(source_before):
|
||||
errors.append(dict(kind="current-app-source-differs-from-built-revision", builtRevision=built_revision, builtSourceManifestSha256=built_source_manifest, actualSourceManifestSha256=manifest_hash(source_before)))
|
||||
warnings = []
|
||||
responses = {}
|
||||
http_checks = []
|
||||
@@ -329,6 +366,15 @@ def main():
|
||||
http_checks.append(dict(url=url, method=method, status=status, curlReturncode=result.returncode, bytes=len(content), location=headers.get("location"), contentType=headers.get("content-type")))
|
||||
return value
|
||||
|
||||
live_health_response = request("/health/ready")
|
||||
live_health = None
|
||||
try:
|
||||
live_health = json.loads(live_health_response["body"])
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
if live_health_response["status"] != 200 or live_health != built_health:
|
||||
errors.append(dict(kind="live-built-health-identity-mismatch", status=live_health_response["status"], expected=built_health, actual=live_health))
|
||||
|
||||
pages = []
|
||||
occurrences = []
|
||||
script_constants = []
|
||||
@@ -361,19 +407,42 @@ def main():
|
||||
errors.append(dict(kind="empty-export-no-html"))
|
||||
|
||||
# Decode every exported raster asset, including unlinked public files.
|
||||
# Files are confined above; PIL verification never executes image content.
|
||||
for entry in before:
|
||||
# Both explicit decoders fail closed; there is no "skip images" fallback.
|
||||
raster_entries = [entry for entry in before if Path(entry["path"]).suffix.lower() in (".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico")]
|
||||
if RASTER_DECODER == "sharp":
|
||||
result = subprocess.run(["node", str(ROOT / "scripts/rebuild-v2/decode-raster-sharp.mjs")], cwd=ROOT,
|
||||
input=json.dumps(dict(root=str(out), files=[e["path"] for e in raster_entries])).encode(), capture_output=True)
|
||||
try:
|
||||
decoded = json.loads(result.stdout)
|
||||
decoded_rows = decoded["results"]
|
||||
if [item.get("file") for item in decoded_rows] != [e["path"] for e in raster_entries]:
|
||||
raise ValueError("Sharp did not return every requested raster in order")
|
||||
for entry, item in zip(raster_entries, decoded_rows):
|
||||
item["sha256"] = entry["sha256"]
|
||||
asset_checks.append(item)
|
||||
if not item.get("valid"):
|
||||
errors.append(dict(kind="invalid-raster-image", file=entry["path"], error=item.get("error"), decoder="sharp"))
|
||||
if result.returncode and not any(not item.get("valid") for item in decoded_rows):
|
||||
errors.append(dict(kind="raster-decoder-process-failed", decoder="sharp", returncode=result.returncode, error=result.stderr.decode(errors="replace")[:2000]))
|
||||
except (ValueError, KeyError, TypeError) as exc:
|
||||
errors.append(dict(kind="raster-decoder-failed", decoder="sharp", error=str(exc), stderr=result.stderr.decode(errors="replace")[:2000]))
|
||||
else:
|
||||
for entry in raster_entries:
|
||||
path = out / entry["path"]
|
||||
if path.suffix.lower() in (".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico"):
|
||||
try:
|
||||
with Image.open(path) as image:
|
||||
width, height = image.size
|
||||
image.verify()
|
||||
asset_checks.append(dict(file=entry["path"], type="raster", valid=True, width=width, height=height, sha256=entry["sha256"]))
|
||||
with Image.open(path) as image:
|
||||
for frame in ImageSequence.Iterator(image):
|
||||
frame.load()
|
||||
asset_checks.append(dict(file=entry["path"], type="raster", valid=True, width=width, height=height, sha256=entry["sha256"], decoder="pillow-verify-and-full-load"))
|
||||
except Exception as exc:
|
||||
asset_checks.append(dict(file=entry["path"], type="raster", valid=False, error=str(exc)))
|
||||
asset_checks.append(dict(file=entry["path"], type="raster", valid=False, error=str(exc), decoder="pillow"))
|
||||
errors.append(dict(kind="invalid-raster-image", file=entry["path"], error=str(exc)))
|
||||
elif path.suffix.lower() == ".pdf":
|
||||
for entry in before:
|
||||
path = out / entry["path"]
|
||||
if path.suffix.lower() == ".pdf":
|
||||
data = path.read_bytes()
|
||||
valid = b"%PDF-" in data[:1024] and b"%%EOF" in data[-2048:]
|
||||
asset_checks.append(dict(file=entry["path"], type="pdf-signature-and-eof", valid=valid, sha256=entry["sha256"]))
|
||||
@@ -546,8 +615,7 @@ def main():
|
||||
errors.append(dict(kind="build-mutated-during-check"))
|
||||
if source_before != source_after:
|
||||
errors.append(dict(kind="source-mutated-during-check"))
|
||||
git = subprocess.run(["git", "rev-parse", "HEAD"], cwd=ROOT, capture_output=True, text=True)
|
||||
report = dict(schemaVersion=1, domain="videoreg.ru", generatedAt=datetime.now(timezone.utc).isoformat(), sourceCommit=git.stdout.strip(), sourceManifestSha256=manifest_hash(source_before), sourceFiles=source_before, exportManifestSha256=manifest_hash(before), exportFileCount=len(before), base=base, origin=args.origin, tlsVerified=False if args.insecure_origin else (True if base.startswith("https://") and all(x["curlReturncode"] == 0 for x in http_checks) else None), browserDOMInspection="not performed by this script; use separate exact-candidate browser evidence", summary=dict(technicalStatus="failed" if errors else "passed", restorationStatus="blocked-unresolved-inventory" if unresolved else "reconciled", acceptance="blocked" if errors or unresolved else "mechanical-checks-only-not-role-approval", htmlFiles=len(pages), contentPages=sum(not p["errorDocument"] for p in pages), HTTPRequests=len(http_checks), localReferences=len(local_refs), emittedExternalOccurrences=len(outbound), activeSourceFiles=len(source_files), inventoryItems=len(inventory), unresolvedInventoryItems=len(unresolved), suspiciousPages=len(warnings), errors=len(errors), decodedRasterAssets=sum(x["type"] == "raster" for x in asset_checks)), pages=pages, assetChecks=asset_checks, duplicateBodies=duplicates, suspiciousCandidates=warnings, errors=errors, localReferences=local_refs, outboundOccurrences=outbound, inertScriptConstants=script_constants, activeSourceReferences=active_occurrences, HTTPChecks=http_checks, legacyRoutes=legacy_results, sourcePublications=source_publications, behavior=behavior, coverage=dict(statusCounts=dict(Counter(x["status"] for x in inventory_results)), items=inventory_results, unresolved=unresolved), limitations=["No external page is fetched by this checker; approvals must contain independent editorial verification.", "HTML/CSS/script-string extraction detects static references. Live JavaScript interactions, crops and browser DOM are checked separately.", "Suspicious thin/spam/error flags require per-page editorial assessment; they are not automatically treated as spam exclusions.", "A reconciled inventory does not establish that the external discovery denominator is complete."])
|
||||
report = dict(schemaVersion=1, domain="videoreg.ru", generatedAt=datetime.now(timezone.utc).isoformat(), sourceCommit=built_revision, repositoryHead=repository_head, builtHealthMetadata=built_health, builtSourceManifestSha256=built_source_manifest, rasterDecoder=RASTER_DECODER, sourceManifestSha256=manifest_hash(source_before), sourceFiles=source_before, exportManifestSha256=manifest_hash(before), exportFileCount=len(before), base=base, origin=args.origin, tlsVerified=False if args.insecure_origin else (True if base.startswith("https://") and all(x["curlReturncode"] == 0 for x in http_checks) else None), browserDOMInspection="not performed by this script; use separate exact-candidate browser evidence", summary=dict(technicalStatus="failed" if errors else "passed", restorationStatus="blocked-unresolved-inventory" if unresolved else "reconciled", acceptance="blocked" if errors or unresolved else "mechanical-checks-only-not-role-approval", htmlFiles=len(pages), contentPages=sum(not p["errorDocument"] for p in pages), HTTPRequests=len(http_checks), localReferences=len(local_refs), emittedExternalOccurrences=len(outbound), activeSourceFiles=len(source_files), inventoryItems=len(inventory), unresolvedInventoryItems=len(unresolved), suspiciousPages=len(warnings), errors=len(errors), decodedRasterAssets=sum(x["type"] == "raster" for x in asset_checks)), pages=pages, assetChecks=asset_checks, duplicateBodies=duplicates, suspiciousCandidates=warnings, errors=errors, localReferences=local_refs, outboundOccurrences=outbound, inertScriptConstants=script_constants, activeSourceReferences=active_occurrences, HTTPChecks=http_checks, legacyRoutes=legacy_results, sourcePublications=source_publications, behavior=behavior, coverage=dict(statusCounts=dict(Counter(x["status"] for x in inventory_results)), items=inventory_results, unresolved=unresolved), limitations=["No external page is fetched by this checker; approvals must contain independent editorial verification.", "HTML/CSS/script-string extraction detects static references. Live JavaScript interactions, crops and browser DOM are checked separately.", "Suspicious thin/spam/error flags require per-page editorial assessment; they are not automatically treated as spam exclusions.", "A reconciled inventory does not establish that the external discovery denominator is complete."])
|
||||
args.report.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.report.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
||||
print(json.dumps(dict(report=str(args.report.relative_to(ROOT) if args.report.is_relative_to(ROOT) else args.report), **report["summary"]), ensure_ascii=False))
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
"""A simulated429 must persist Retry-After and prevent subsequent network calls."""
|
||||
import tempfile,unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
from types import SimpleNamespace
|
||||
import fetch
|
||||
class RateLimit(unittest.TestCase):
|
||||
def test_stop_all_following_wayback_fetches(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root=Path(directory);raw=root/'raw';raw.mkdir()
|
||||
def respond(cmd,**kwargs):
|
||||
Path(cmd[cmd.index('-D')+1]).write_text('HTTP/2 429\nRetry-After: 120\n')
|
||||
Path(cmd[cmd.index('-o')+1]).write_text('Too Many Requests')
|
||||
return SimpleNamespace(stdout='429\nhttps://web.archive.org/web/test',stderr='',returncode=0)
|
||||
with patch.object(fetch,'ROOT',root),patch.object(fetch,'RAW',raw),patch.object(fetch.subprocess,'run',side_effect=respond) as network:
|
||||
result=fetch.fetch('https://web.archive.org/web/test','first.html')
|
||||
self.assertEqual(result['httpStatus'],'429')
|
||||
self.assertIn('120',(raw/'wayback-rate-limit.json').read_text())
|
||||
with self.assertRaisesRegex(RuntimeError,'stop marker'):fetch.fetch('https://web.archive.org/cdx/search/cdx','second.json')
|
||||
self.assertEqual(network.call_count,1)
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,22 @@
|
||||
/** Real positive and truncated-image failure behavior, using only temp fixtures. */
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtemp, writeFile, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import sharp from 'sharp';
|
||||
import { decodeBatch } from './decode-raster-sharp.mjs';
|
||||
|
||||
const root = await mkdtemp(join(tmpdir(), 'videoreg-v2-raster-fixture-'));
|
||||
try {
|
||||
const good = await sharp({ create: { width: 64, height: 32, channels: 3, background: '#17382f' } }).png().toBuffer();
|
||||
await writeFile(join(root, 'good.png'), good);
|
||||
await writeFile(join(root, 'truncated.png'), good.subarray(0, 32));
|
||||
const report = await decodeBatch({ root, files: ['good.png', 'truncated.png'] });
|
||||
assert.equal(report.results[0].valid, true, 'Valid PNG must decode all pixels');
|
||||
assert.equal(report.results[0].width, 64);
|
||||
assert.equal(report.results[0].height, 32);
|
||||
assert.equal(report.results[1].valid, false, 'Truncated PNG must fail, not be skipped or treated as metadata-only pass');
|
||||
process.stdout.write(JSON.stringify({ test: 'full-raster-decode-positive-and-corruption', status: 'passed', results: report.results }) + '\n');
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/** Fully decode all raster pixels with npm-lockfile-pinned sharp; no network. */
|
||||
import sharp from 'sharp';
|
||||
import { realpath } from 'node:fs/promises';
|
||||
import { resolve, sep } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
sharp.cache(false);
|
||||
sharp.concurrency(1);
|
||||
|
||||
export async function decodeBatch({ root, files }) {
|
||||
if (sharp.versions.sharp !== '0.34.5') {
|
||||
throw new Error(`Expected lockfile sharp0.34.5, found ${sharp.versions.sharp}`);
|
||||
}
|
||||
if (typeof root !== 'string' || !Array.isArray(files) || files.length > 10000) {
|
||||
throw new Error('Expected a public root and a bounded file array');
|
||||
}
|
||||
const boundary = await realpath(root);
|
||||
const results = [];
|
||||
for (const file of files) {
|
||||
try {
|
||||
const candidate = await realpath(resolve(boundary, file));
|
||||
if (!candidate.startsWith(boundary + sep)) throw new Error('Raster path outside public root');
|
||||
const image = sharp(candidate, { failOn: 'error', animated: true, limitInputPixels: 64000000 });
|
||||
const metadata = await image.metadata();
|
||||
// metadata() alone is insufficient: force actual decode of every pixel.
|
||||
const { info } = await image.raw().toBuffer({ resolveWithObject: true });
|
||||
results.push({ file, type: 'raster', valid: true,
|
||||
width: info.width, height: info.height, format: metadata.format,
|
||||
pages: metadata.pages ?? 1, decodedBytes: info.size,
|
||||
decoder: `sharp${sharp.versions.sharp}/libvips${sharp.versions.vips}` });
|
||||
} catch (error) {
|
||||
results.push({ file, type: 'raster', valid: false, error: String(error.message), decoder: 'sharp0.34.5' });
|
||||
}
|
||||
}
|
||||
return { decoder: 'sharp', version: sharp.versions.sharp, results };
|
||||
}
|
||||
|
||||
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
try {
|
||||
const chunks = [];
|
||||
let size = 0;
|
||||
for await (const chunk of process.stdin) {
|
||||
size += chunk.length;
|
||||
if (size > 4000000) throw new Error('Raster manifest exceeds 4MB');
|
||||
chunks.push(chunk);
|
||||
}
|
||||
const report = await decodeBatch(JSON.parse(Buffer.concat(chunks).toString('utf8')));
|
||||
process.stdout.write(JSON.stringify(report) + '\n');
|
||||
if (report.results.some(item => !item.valid)) process.exitCode = 1;
|
||||
} catch (error) {
|
||||
process.stderr.write(String(error.stack ?? error) + '\n');
|
||||
process.exitCode = 2;
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse,hashlib,json,subprocess,time
|
||||
import argparse,hashlib,json,subprocess,time,re
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlencode
|
||||
ROOT=Path(__file__).resolve().parents[2]
|
||||
RAW=ROOT/'docs/rebuild-v2/raw';RAW.mkdir(parents=True,exist_ok=True)
|
||||
def fetch(url,name,timeout=65):
|
||||
rate_flag=RAW/'wayback-rate-limit.json'
|
||||
if 'web.archive.org' in url and rate_flag.exists():raise RuntimeError('Wayback HTTP429 stop marker exists; no further requests on currentIP, no bypass.')
|
||||
dest=RAW/name;headers=dest.with_suffix(dest.suffix+'.headers')
|
||||
started=time.time()
|
||||
r=subprocess.run(['curl','--compressed','-sS','-L','--max-time',str(timeout),'-D',str(headers),'-o',str(dest),'-w','%{http_code}\n%{url_effective}',url],capture_output=True,text=True)
|
||||
@@ -15,6 +17,9 @@ def fetch(url,name,timeout=65):
|
||||
if not object_file.exists():object_file.write_bytes(b)
|
||||
rec=dict(url=url,raw=str(dest.relative_to(ROOT)),immutableRaw=str(object_file.relative_to(ROOT)),sha256=hashlib.sha256(b).hexdigest(),bytes=len(b),httpStatus=parts[0] if parts else None,effectiveUrl=parts[1] if len(parts)>1 else None,curlExit=r.returncode,error=r.stderr.strip(),checkedAt=time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()),seconds=round(time.time()-started,2))
|
||||
with (RAW/'requests.jsonl').open('a') as f:f.write(json.dumps(rec,ensure_ascii=False)+'\n')
|
||||
if 'web.archive.org' in url and rec['httpStatus']=='429':
|
||||
retry=re.findall(r'(?im)^retry-after:\s*(.*)$',headers.read_text(errors='replace'))
|
||||
rate_flag.write_text(json.dumps(dict(url=url,observedAt=rec['checkedAt'],retryAfterRaw=retry,action='Stop all Wayback requests on currentIP; no bypass'),indent=2)+'\n')
|
||||
print(json.dumps({k:rec[k] for k in ['raw','httpStatus','bytes','curlExit','error']}),flush=True)
|
||||
return rec
|
||||
if __name__=='__main__':
|
||||
|
||||
@@ -88,13 +88,15 @@ for key in sorted(set(by)|set(new_leads)):
|
||||
title=item.get('_title') if item else (lead or {}).get('context')
|
||||
entry=dict(originalUrl=item['originalUrl'] if item else lead['originalUrl'],normalizedPath=key,type=kind,chosenSnapshot=item.get('_actualSnapshot',item['snapshot']) if item and valid else None,requestedSnapshot=item.get('snapshot') if item else None,fetchStatus='validated-html-body' if valid else ('not-fetched-utility' if status.startswith('excluded') else 'unresolved'),rawFile=item['rawFile'] if valid else None,rawSha256=item.get('_sha') if item else None,title=title,rawVisibleTextChars=len(item.get('_text','')) if item else 0,currentDestination=dest,editorialAction=action,publicationStatus=status,exclusionOrUnresolvedReason=reason or 'No validated source body recovered after actual capture/version/URL attempts; restoration remains blocked.',discoveredFrom=(lead or {}).get('foundOn',[]))
|
||||
entries.append(entry)
|
||||
from semrush_inventory import merge as merge_semrush_observed
|
||||
entries=merge_semrush_observed(entries)
|
||||
(D/'url-inventory.json').write_text(json.dumps(entries,ensure_ascii=False,indent=2)+'\n')
|
||||
(D/'outbound-links.json').write_text(json.dumps(dict(scope='Every external HTML attribute and inline URL in all fetched source pages. Public-source/build/DOM stages appended by verification script.',links=source_outbound),ensure_ascii=False,indent=2)+'\n')
|
||||
semrush=D/'semrush';semrush.mkdir(exist_ok=True)
|
||||
(semrush/'recovery-questions.json').write_text(json.dumps(dict(domain='videoreg.ru',scope=['apex','www'],status='awaiting actual coordinator Noxtools/Semrush evidence; not inspected by domain executor',missing=[dict(path=x['normalizedPath'],url=x['originalUrl'],title=x['title'],source=x['discoveredFrom']) for x in entries if x['publicationStatus'].startswith('unresolved')],questions=['Lost backlink targets beyond the CDX/HTML link union?','Exact titles and context for predpr.shtml, moves.htm, law1.htm, law2.htm and unindexed product/topic paths?','Separate manufacturer technical pages from later casino/real-estate/SEO anchors.','Record database, report scope/date, limits and first/last-seen dates.'],currentKnownEvidence='CDX883HTMLcaptures;259allresourceURLkeys; body recovery recorded per URL; all distinct pre/post2015 versions tried on missing indexed content.'),ensure_ascii=False,indent=2)+'\n')
|
||||
(semrush/'recovery-questions.json').write_text(json.dumps(dict(domain='videoreg.ru',scope=['apex','www'],status='actual83URLtranscript received and reconciled;17metadata rows;6reportedrowsunseen; executor did nottakeoversharedUI',missing=[dict(path=x['normalizedPath'],url=x['originalUrl'],title=x['title'],source=x['discoveredFrom']) for x in entries if x['publicationStatus'].startswith('unresolved')],questions=['Lost backlink targets beyond the CDX/HTML link union?','Exact titles and context for predpr.shtml, moves.htm, law1.htm, law2.htm and unindexed product/topic paths?','Separate manufacturer technical pages from later casino/real-estate/SEO anchors.','Record database, report scope/date, limits and first/last-seen dates.'],currentKnownEvidence='CDX883HTMLcaptures;259allresourceURLkeys; body recovery recorded per URL; all distinct pre/post2015 versions tried on missing indexed content.'),ensure_ascii=False,indent=2)+'\n')
|
||||
counts=collections.Counter(e['publicationStatus'] for e in entries);meaningful=[e for e in entries if not e['publicationStatus'].startswith('excluded')]
|
||||
body_captures=sum('_sha'in x for x in plan)
|
||||
text=f'''# Coverage V2 — known denominator, unresolved restoration\n\nCDX discovery: 883 HTML captures across 2007–2025; 121 collapsed HTML URL keys and 259 resource URL keys. Removing phpBB sid duplicates gives101 original normalized HTML URLs. Full CDX JSON has no resume key, so returned index is complete for the actual query (all883 originals were HTTP;528www and355apex; no HTTPS200 captures returned). Linked original URLs from every fetched body expand the known inventory. Unfetched bodies may contain further undiscovered links: this is a **known lower bound**, not a complete historical-site claim.\n\nKnown normalized URLs in inventory: **{len(entries)}**. Meaningful/non-utility denominator (including unresolved): **{len(meaningful)}**. Actual validated fetched HTML bodies: **{body_captures}** (includes commercial/navigation pages; not all are published articles). Publication dispositions:\n\n'''+''.join(f'- {k}: {v}\n' for k,v in sorted(counts.items()))+'''\nEach entry has URL/type/snapshot/raw hash/title/body size/destination/editorial action/status/reason in `url-inventory.json`. `edited-recovered` counts source URLs, not unique articles; canonical merges and verified equivalents are separate. Typed article pages include new HTML document companions whose complete original PDFs are available; counts must not be presented as16 historic HTML bodies.\n\nImportant unresolved items include missing historical topic bodies, original installation photographs, unrecovered video bytes and partial GPSsampleZIP. The January2008 SVK002 journal test PDF is now completely recovered (3pages). All alternative versions and URL variants actually attempted are in raw/requests.jsonl. These gaps and pending Semrush reconciliation remain mandatory V2 blockers. No historical article is synthesized from a backlink anchor/title. V1 modern guides/retail cards do not enter recovery counts.\n'''
|
||||
text=f'''# Coverage V2 — known denominator, unresolved restoration\n\nCDX discovery: 883 HTML captures across 2007–2025; 121 collapsed HTML URL keys and 259 resource URL keys. Removing phpBB sid duplicates gives101 original normalized HTML URLs. Full CDX JSON has no resume key, so returned index is complete for the actual query (all883 originals were HTTP;528www and355apex; no HTTPS200 captures returned). Linked original URLs from every fetched body expand the known inventory. Unfetched bodies may contain further undiscovered links: this is a **known lower bound**, not a complete historical-site claim.\n\nKnown normalized URLs in inventory: **{len(entries)}**. Meaningful/non-utility denominator (including unresolved): **{len(meaningful)}**. Actual validated fetched HTML bodies: **{body_captures}** (includes commercial/navigation pages; not all are published articles). Publication dispositions:\n\n'''+''.join(f'- {k}: {v}\n' for k,v in sorted(counts.items()))+'''\nEach entry has URL/type/snapshot/raw hash/title/body size/destination/editorial action/status/reason in `url-inventory.json`. `edited-recovered` counts source URLs, not unique articles; canonical merges and verified equivalents are separate. Typed article pages include new HTML document companions whose complete original PDFs are available; counts must not be presented as16 historic HTML bodies.\n\nImportant unresolved items include missing historical topic bodies, original installation photographs, unrecovered video bytes and partial GPSsampleZIP. The January2008 SVK002 journal test PDF is now completely recovered (3pages). All alternative versions and URL variants actually attempted are in raw/requests.jsonl. Semrush83URLtranscript adds explicit epoch/encoded/malformed/fragment-unverified leads; no URL-only Blox/spam exclusion is assumed. These gaps and pending Semrush reconciliation remain mandatory V2 blockers. No historical article is synthesized from a backlink anchor/title. V1 modern guides/retail cards do not enter recovery counts.\n'''
|
||||
(D/'coverage.md').write_text(text)
|
||||
# Freeze successful source bytes in content-addressed files; retain original friendly filenames.
|
||||
objects=RAW/'objects';objects.mkdir(exist_ok=True)
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Small evidence-led batch: two exact metadata queries and at most five replays.
|
||||
Stop all Wayback work on HTTP429; no alternate host/IP, proxy or limit bypass.
|
||||
"""
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlencode
|
||||
from bs4 import BeautifulSoup
|
||||
import sys,json,time,re
|
||||
sys.path.insert(0,str(Path(__file__).parent))
|
||||
from fetch import fetch
|
||||
P=Path(__file__).resolve().parents[2];D=P/'docs/rebuild-v2';RAW=D/'raw';flag=RAW/'wayback-rate-limit.json'
|
||||
leads=[dict(key='topic196',url='http://www.videoreg.ru/forum/viewtopic.php?t=196',title='Применение доказательств',why='Exact Semrush83 target; actual recovered forumf2 listing supplies same technical/legal topic title, no body invented.',replays=['https://web.archive.org/web/2012id_/http://www.videoreg.ru:80/forum/viewtopic.php?t=196','https://web.archive.org/web/2009id_/http://videoreg.ru:80/forum/viewtopic.php?t=196']),dict(key='product138',url='http://www.videoreg.ru/shop/index.php?productID=138',title='СВК-005',why='Exact Semrush83 target; recovered category79 links this model/card. Category summary does not prove full product body.',replays=['https://web.archive.org/web/2009id_/http://www.videoreg.ru:80/shop/index.php?productID=138','https://web.archive.org/web/2012id_/http://videoreg.ru:80/shop/index.php?productID=138']),dict(key='svk007-hyphen-zip',url='http://videoreg.ru/download/doc/svk-007-instr.zip',title='svk-007-instr.zip',why='Actual resourceCDX20160914115702 and original document link. Differently named underscore manual is not assumed identical.',replays=['https://web.archive.org/web/20160914115702id_/http://videoreg.ru/download/doc/svk-007-instr.zip'])]
|
||||
requests=[]
|
||||
def bounded(url,name):
|
||||
if flag.exists():raise RuntimeError('Wayback429 stop marker exists; no further calls on this IP.')
|
||||
r=fetch(url,name,90);requests.append(r)
|
||||
if r['httpStatus']=='429':
|
||||
headers=(P/r['raw']).with_suffix(Path(r['raw']).suffix+'.headers').read_text(errors='replace');retry=re.findall(r'(?im)^retry-after:\s*(.*)$',headers);flag.write_text(json.dumps(dict(url=url,observedAt=r['checkedAt'],retryAfterRaw=retry,action='Stop all Wayback requests on currentIP; no bypass'),indent=2)+'\n');raise RuntimeError('HTTP429; stopped whole Wayback batch.')
|
||||
time.sleep(2)
|
||||
return r
|
||||
result=dict(scope='3actualcontent/documenttargets; no bulkuniformretry',leads=leads,requests=requests,acceptedNewBodies=[])
|
||||
try:
|
||||
for lead in leads[:2]:
|
||||
u='https://web.archive.org/cdx/search/cdx?'+urlencode(dict(url=lead['url'],output='json',collapse='digest',filter='statuscode:200',fl='timestamp,original,mimetype,statuscode,digest,length'))
|
||||
bounded(u,'priority83-'+lead['key']+'-cdx.json')
|
||||
for lead in leads:
|
||||
lead['attempts']=[]
|
||||
for i,u in enumerate(lead['replays']):
|
||||
r=bounded(u,f'priority83-{lead["key"]}-{i}.bin');lead['attempts'].append(r)
|
||||
if r['curlExit']==0 and r['httpStatus']=='200' and r['bytes']>500:
|
||||
f=P/r['raw']
|
||||
if lead['key']=='svk007-hyphen-zip':
|
||||
import zipfile
|
||||
try:
|
||||
with zipfile.ZipFile(f) as z:
|
||||
valid=z.testzip() is None;lead['members']=z.namelist()
|
||||
if valid:lead['candidateRaw']=r['raw'];lead['candidateKind']='validated ZIP, members require full content review';break
|
||||
except Exception as e:lead['validationError']=str(e)
|
||||
else:
|
||||
s=BeautifulSoup(f.read_bytes().decode('cp1251',errors='replace'),'html.parser');text=s.get_text(' ',strip=True)
|
||||
lead['returnedTitle']=s.title.get_text(' ',strip=True) if s.title else None;lead['bodyChars']=len(text)
|
||||
if len(text)>1000 and not re.search('wayback machine|not found|cannot be crawled|too many requests|just a moment',text,re.I):lead['candidateRaw']=r['raw'];lead['candidateKind']='HTML candidate requiring actual full body review';break
|
||||
except Exception as e:result['stopped']=str(e)
|
||||
(D/'semrush/priority83-recovery-batch.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n');print('BATCH',[(r['httpStatus'],r['bytes'],r['curlExit']) for r in requests],result.get('stopped',''))
|
||||
@@ -12,8 +12,12 @@ for row in raw['rows']:
|
||||
k=norm(row['url']);found=by.get(k);status=found['publicationStatus'] if found else 'unresolved-new-lead'
|
||||
if row['classification']=='later_expired_domain_state':status='later-state-not-original-body'
|
||||
rows.append(dict(observed=row,normalizedPath=k,matchedInventoryUrl=found['originalUrl'] if found else None,recoveryDisposition=status,rawFile=found['rawFile'] if found else None,sourceHash=found['rawSha256'] if found else None,currentDestination=found['currentDestination'] if found else None,bodyRecoveredFromAnchor=False,review='Specific target reconciled to actual source inventory; metrics not treated as body proof'))
|
||||
extra=[('/moves.htm','Универсальный цифровой видеорегистратор СВК','recovered-original-Russia1clip-context'),('/autopredpr.shtml',None,'matched'),('/demo.shtml',None,'unresolved-media'),('/shop/index.php?productID=133',None,'matched'),('/shop/index.php?productID=138',None,'unresolved'),('/forum/viewtopic.php?t=196',None,'unresolved'),('/forum/viewforum.php?f=1',None,'navigation-only'),('/account',None,'excluded-later-unrelated-Blox-state'),('/join',None,'excluded-later-unrelated-Blox-state'),('/withdraw',None,'excluded-later-unrelated-Blox-state')]
|
||||
extra=[('/moves.htm','Универсальный цифровой видеорегистратор СВК','recovered-original-Russia1clip-context'),('/autopredpr.shtml',None,'matched'),('/demo.shtml',None,'unresolved-media'),('/shop/index.php?productID=133',None,'matched'),('/shop/index.php?productID=138',None,'unresolved'),('/forum/viewtopic.php?t=196',None,'unresolved'),('/forum/viewforum.php?f=1',None,'navigation-only'),('/account',None,'unresolved-epoch-body-not-verified'),('/join',None,'unresolved-epoch-body-not-verified'),('/withdraw',None,'unresolved-epoch-body-not-verified')]
|
||||
report=dict(domain='videoreg.ru',evidenceOrigin='Coordinator inspected Noxtools/Semrush in shared built-in browser; this executor ingested actual supplied transcription without taking over session',reportUrl=raw['reportUrl'],additionalEvidenceFiles=['observed-anchors.partial.json','observed-lost-vital.json','referrer-verification.json'],reportedTotal=raw['reportedTotal'],actualDOMRowsReported=raw['actualDOMRowsReportedByParent'],transcribedRows=raw['transcribedRows'],complete=False,scopeLimitation=raw['scopeLimit'],originalExportSha256=hashlib.sha256((D/'observed-indexed-pages.json').read_bytes()).hexdigest(),rows=rows,additionalCoordinatorMessageLeads=[dict(url='http://www.videoreg.ru'+k,title=t,disposition=s,evidence='Direct coordinator message2026-10-26; exact per-row metrics/date not supplied') for k,t,s in extra],remainingRequirements=['Remaining66observedDOM rows and6unloaded reported rows not provided as full export','Anchors52DOM/3transcribed; LostVital18DOM/6transcribed.5actualreferrersfetched;3HTTP200,2unavailable. Full rowtranscriptions and remainingreferrers remain mandatory.','Unresolved target bodies/media must be recovered from actual sources; no text synthesized from anchors'])
|
||||
all83=D/'observed-indexed-all83-urls.json'
|
||||
if all83.exists():
|
||||
report.update(urlRowsTranscribed=83,metadataRowsTranscribed=17,reportedButUnseen=6,exactUrlReconciliation='indexed83-reconciliation.json',urlTranscriptSha256=hashlib.sha256(all83.read_bytes()).hexdigest(),expandedInventoryKnownUrls=len(inv),currentUnresolvedTargets=sum(x['publicationStatus'].startswith('unresolved') for x in inv),lateEpochPolicy='URL-only does not prove Blox/expiry/spam; epoch-unverifiedtargets retainedunresolved.')
|
||||
report['remainingRequirements']=['SixreportedURLrowsnotobserved; nofabrication','Metadatafor17only;52Anchorrows/3transcribedand18LostVitalrows/6transcribed remainpartial','Actualunresolvedbodiesandunknown-epochtargets remainmandatory; no URL/title synthesis']
|
||||
(D/'reconciliation.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
|
||||
(D/'scope.md').write_text('# Semrush / Noxtools — actual partial scope\n\nCoordinator used the shared built-in browser. Report total89, actualDOM83, supplied transcription17selected rows. This executor ingested exactly those17 and the explicit additional coordinator message leads; it did not independently inspect the UI or manufacture the remaining rows.\n\n`reconciliation.json` maps each supplied target to actual raw body/status. Late expiry and Blox account/join/withdraw states do not replace original technical content. Backlink counts are not recovered text.\n\nMandatory issue videoreg-7oy.7 stays open: complete exported row coverage and actual referringURL/anchor contexts are still missing.\n')
|
||||
print('Semrush matched observed rows',len(rows),'of reported',raw['reportedTotal'],'scope remains partial')
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Merge observed exact variants without claiming their bodies or epoch."""
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit,parse_qsl,urlencode
|
||||
import json
|
||||
D=Path(__file__).resolve().parents[2]/'docs/rebuild-v2'
|
||||
def merge(entries):
|
||||
file=D/'semrush/observed-indexed-all83-urls.json'
|
||||
if not file.exists():return entries
|
||||
observed=json.loads(file.read_text());by={r['normalizedPath']:r for r in entries}
|
||||
for order,url in enumerate(observed['urlsInObservedOrder'],1):
|
||||
u=urlsplit(url);pairs=[(k,v) for k,v in parse_qsl(u.query) if k!='sid'];key=u.path+('?' +urlencode(sorted(pairs)) if pairs else '')+('#'+u.fragment if u.fragment else '')
|
||||
if key not in by:
|
||||
status='unresolved-epoch';kind='semrush-content-epoch-unverified'
|
||||
if u.fragment:status='unresolved-fragment';kind='semrush-fragment-target'
|
||||
elif '%20' in u.path:status='unresolved-encoded-path';kind='semrush-encoded-path-target'
|
||||
elif '%29' in u.query:status='unresolved-malformed-query';kind='semrush-malformed-query-target'
|
||||
row=dict(originalUrl=url,normalizedPath=key,type=kind,chosenSnapshot=None,requestedSnapshot=None,fetchStatus='body-unverified',rawFile=None,rawSha256=None,title=None,rawVisibleTextChars=0,currentDestination=None,editorialAction='Identify actual body and epoch; do not synthesize from URL/anchor or silently normalize malformed query/fragment.',publicationStatus=status,exclusionOrUnresolvedReason='Exact observed Semrush URL only. No validated body establishes technical purpose, Blox/expiry/spam epoch or lawful editorial exclusion.',discoveredFrom=['Semrush actual83URLtranscript; metadata only17rows; reported89/sixunseen'],observedSemrushVariants=[])
|
||||
entries.append(row);by[key]=row
|
||||
row=by[key];variants=row.setdefault('observedSemrushVariants',[])
|
||||
if not any(v['url']==url for v in variants):variants.append(dict(url=url,observedOrder=order,exactVariantBodyVerified=False,epochVerified=False,meaning='Path correspondence alone does not establish body or epoch at this exact scheme/www/query/fragment.'))
|
||||
return sorted(entries,key=lambda r:r['normalizedPath'])
|
||||
@@ -1,7 +1,7 @@
|
||||
from pathlib import Path
|
||||
import json,datetime,collections
|
||||
P=Path(__file__).resolve().parents[2];D=P/'docs/rebuild-v2';b=json.loads((D/'evidence/built-crawl.json').read_text());local=json.loads((P/'.local-run/server.json').read_text());inv=json.loads((D/'url-inventory.json').read_text());media=json.loads((D/'evidence/media-validation.json').read_text())
|
||||
x=dict(domain='videoreg.ru',epic='videoreg-7oy',updatedAt=datetime.datetime.now(datetime.timezone.utc).isoformat(),stage='candidate-R2-five-role-reviewed; restoration-blocked',v1Acceptance='user rejected; all prior PASS superseded',rollbackRef='videoreg-v1-rejected-20261026',roles=dict(designer='/root/v2_designer',additionalDesigner='/root/designer',creative_director='/root/v2_creative_director',content_manager='/root/v2_content_manager',illustrator='/root/v2_illustrator',programmer_expert='/root/v2_programmer'),coverage=dict(cdxHtmlCaptures=883,cdxHtmlUrlKeys=121,cdxAllResourceUrlKeys=259,validatedFetchedHtmlBodies=30,typedEditedArticlesInSource=28,contentHtmlPages=33,allExportHtmlFiles=35,validOriginalPdfManuals=4,validOriginalJournalReviewPdfs=1,primaryMediaResources=136,primaryMediaValidationCounts=media['counts'],additionalSampleHostJpegDecoded=158,salvagedCompleteGpsJpeg=4,originalSampleFramesUnavailable=25,knownUrlInventory=len(inv),meaningfulNonExcludedUrls=138,publicationCounts=dict(collections.Counter(i['publicationStatus'] for i in inv)),inventoryComplete=False),defects=['videoreg-7oy.8:99unresolvedHTML/linked inventory entries plus1partialGPSZIP,63unresolvedprimarymediaresources and25sampleJPEG gaps; no fabricated bodies','videoreg-7oy.7:Semrush actualtranscriptionspartial Indexed17/89,Anchors3/52,LostVital6/18; fullreconciliationblocked','videoreg-7oy.4/.1:wholecorpusandeditorialacceptanceblocked; specificpublishedsubset reviewed','videoreg-7oy.10:V2notdeployed; publicapextrustedTLS200stillV1;wwwcurl60'],local=local,sourceCommit=b['sourceCommit'],appSourceManifestSha256=b['sourceManifestSha256'],buildHash=b['exportManifestSha256'],technicalChecks=b['summary'],browser=dict(views=68,distinctPaths=34,viewports=[360,1440],overflow=0,brokenImages=0,runtimeErrors=0,functionalChecks=15),reports=['docs/rebuild-v2/url-inventory.json','docs/rebuild-v2/coverage.md','docs/rebuild-v2/editorial-ledger.json','docs/rebuild-v2/outbound-links.json','docs/rebuild-v2/evidence/built-crawl.json','docs/rebuild-v2/evidence/candidate-r2/browser-pages.json','docs/rebuild-v2/semrush/reconciliation.json'],production=dict(v2Deployed=False,image='git.pryanik.synology.me/huncode/videoreg.ru:9b5b080e6019@sha256:2fb63f2666d7c57643328aae1e76cdc5c3e498f704e007a7c57f2fecb033053e',publicApexTLS='verifiedHTTP200V1',publicWwwTLS='curl60',evidence='docs/rebuild-v2/evidence/production-refresh.json'),semrush=dict(status='actual coordinator evidence ingested; mandatorypartialscope',indexed=dict(reported=89,DOM=83,transcribed=17),anchors=dict(reported=52,DOM=52,transcribed=3),lostVital=dict(reported=18,DOM=18,transcribed=6),referringSourcesIndependentlyAttempted=5,referringSourcesHTTP200=3),acceptance='BLOCKED; noV2PASSorproductionpublish')
|
||||
x=dict(domain='videoreg.ru',epic='videoreg-7oy',updatedAt=datetime.datetime.now(datetime.timezone.utc).isoformat(),stage='candidate-R2-five-role-reviewed; restoration-blocked',v1Acceptance='user rejected; all prior PASS superseded',rollbackRef='videoreg-v1-rejected-20261026',roles=dict(designer='/root/v2_designer',additionalDesigner='/root/designer',creative_director='/root/v2_creative_director',content_manager='/root/v2_content_manager',illustrator='/root/v2_illustrator',programmer_expert='/root/v2_programmer'),coverage=dict(cdxHtmlCaptures=883,cdxHtmlUrlKeys=121,cdxAllResourceUrlKeys=259,validatedFetchedHtmlBodies=30,typedEditedArticlesInSource=28,contentHtmlPages=33,allExportHtmlFiles=35,validOriginalPdfManuals=4,validOriginalJournalReviewPdfs=1,primaryMediaResources=136,primaryMediaValidationCounts=media['counts'],additionalSampleHostJpegDecoded=158,salvagedCompleteGpsJpeg=4,originalSampleFramesUnavailable=25,knownUrlInventory=len(inv),meaningfulNonExcludedUrls=sum(not i['publicationStatus'].startswith('excluded') for i in inv),publicationCounts=dict(collections.Counter(i['publicationStatus'] for i in inv)),inventoryComplete=False),defects=['videoreg-7oy.8:119unresolvedtargets(99baselineHTML/linked +20newSemrushunverifiedepoch/fragment/query/path) plus1partialGPSZIP,63unresolvedprimarymediaresources and25sampleJPEG gaps; no fabricated bodies','videoreg-7oy.7:Semrush actualtranscriptionspartial Indexed83exactURLs/89reported,17metadata;Anchors3/52,LostVital6/18; fullreconciliationblocked','videoreg-7oy.4/.1:wholecorpusandeditorialacceptanceblocked119targets; specificpublishedsubset reviewed','videoreg-7oy.10:V2notdeployed; publicapextrustedTLS200stillV1;wwwcurl60','videoreg-7oy.11:remoteCI1321failedPyPIreadtimeout; offlineverificationfixinprogress'],local=local,sourceCommit=b['sourceCommit'],appSourceManifestSha256=b['sourceManifestSha256'],buildHash=b['exportManifestSha256'],technicalChecks=b['summary'],browser=dict(views=68,distinctPaths=34,viewports=[360,1440],overflow=0,brokenImages=0,runtimeErrors=0,functionalChecks=15),reports=['docs/rebuild-v2/url-inventory.json','docs/rebuild-v2/coverage.md','docs/rebuild-v2/editorial-ledger.json','docs/rebuild-v2/outbound-links.json','docs/rebuild-v2/evidence/built-crawl.json','docs/rebuild-v2/evidence/candidate-r2/browser-pages.json','docs/rebuild-v2/semrush/reconciliation.json','docs/rebuild-v2/semrush/indexed83-reconciliation.json','docs/rebuild-v2/semrush/priority83-recovery-batch.json','docs/rebuild-v2/reviews/designer-original-reviewer-final.md','docs/rebuild-v2/reviews/creative-candidate.md','docs/rebuild-v2/reviews/content-candidate.md','docs/rebuild-v2/reviews/illustrator-candidate.md','docs/rebuild-v2/reviews/programmer-candidate.md'],production=dict(v2Deployed=False,image='git.pryanik.synology.me/huncode/videoreg.ru:9b5b080e6019@sha256:2fb63f2666d7c57643328aae1e76cdc5c3e498f704e007a7c57f2fecb033053e',publicApexTLS='verifiedHTTP200V1',publicWwwTLS='curl60',evidence='docs/rebuild-v2/evidence/production-refresh.json'),semrush=dict(status='actual coordinator evidence ingested; mandatorypartialscope',indexed=dict(reported=89,DOM=83,urlRowsTranscribed=83,metadataRowsTranscribed=17,reportedButUnseen=6),anchors=dict(reported=52,DOM=52,transcribed=3),lostVital=dict(reported=18,DOM=18,transcribed=6),referringSourcesIndependentlyAttempted=5,referringSourcesHTTP200=3),acceptance='BLOCKED; noV2PASSorproductionpublish')
|
||||
(D/'STATUS.json').write_text(json.dumps(x,ensure_ascii=False,indent=2)+'\n')
|
||||
y=dict(domain=x['domain'],stage=x['stage'],epic=x['epic'],statusFile=str((D/'STATUS.json').resolve()),local=local,sourceCommit=x['sourceCommit'],buildHash=x['buildHash'],coverage=x['coverage'],openMandatoryBlocks=x['defects'],semrush=x['semrush'],production=x['production'],acceptance=x['acceptance'])
|
||||
Path('/Users/gavrilovdev/tmp/pupline/site-restoration-status/videoreg.ru.json').write_text(json.dumps(y,ensure_ascii=False,indent=2)+'\n')
|
||||
|
||||
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
# Offline verification dependencies
|
||||
|
||||
Vendored exact runtime sources: Beautiful Soup4.15.0, Soup Sieve3.0.4 and typing_extensions4.16.0, copied from this project’s pinned recovery environment. Upstream distribution metadata, copyright and license files are retained unchanged. `manifest.json` records every included file SHA-256. Verify with `python3 -S scripts/rebuild-v2/verify-vendor.py`.
|
||||
|
||||
CI sets PYTHONPATH to this directory and downloads nothing from PyPI. The crawler explicitly uses Python’s built-in html.parser, not optional lxml/html5lib builders. Bytecode caches are excluded. No Pillow/Mac native binaries are vendored: CI uses the lockfile-pinned sharp0.34.5 installed by npm ci and fully decodes every raster. Local default remains Pillow.
|
||||
@@ -0,0 +1,123 @@
|
||||
Metadata-Version: 2.4
|
||||
Name: beautifulsoup4
|
||||
Version: 4.15.0
|
||||
Summary: Screen-scraping library
|
||||
Project-URL: Download, https://www.crummy.com/software/BeautifulSoup/bs4/download/
|
||||
Project-URL: Homepage, https://www.crummy.com/software/BeautifulSoup/bs4/
|
||||
Author-email: Leonard Richardson <leonardr@segfault.org>
|
||||
License: MIT License
|
||||
License-File: AUTHORS
|
||||
License-File: LICENSE
|
||||
Keywords: HTML,XML,parse,soup
|
||||
Classifier: Development Status :: 5 - Production/Stable
|
||||
Classifier: Intended Audience :: Developers
|
||||
Classifier: License :: OSI Approved :: MIT License
|
||||
Classifier: Programming Language :: Python
|
||||
Classifier: Programming Language :: Python :: 3
|
||||
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
||||
Classifier: Topic :: Text Processing :: Markup :: HTML
|
||||
Classifier: Topic :: Text Processing :: Markup :: SGML
|
||||
Classifier: Topic :: Text Processing :: Markup :: XML
|
||||
Requires-Python: >=3.7.0
|
||||
Requires-Dist: soupsieve>=1.6.1
|
||||
Requires-Dist: typing-extensions>=4.0.0
|
||||
Provides-Extra: cchardet
|
||||
Requires-Dist: cchardet; extra == 'cchardet'
|
||||
Provides-Extra: chardet
|
||||
Requires-Dist: chardet; extra == 'chardet'
|
||||
Provides-Extra: charset-normalizer
|
||||
Requires-Dist: charset-normalizer; extra == 'charset-normalizer'
|
||||
Provides-Extra: html5lib
|
||||
Requires-Dist: html5lib; extra == 'html5lib'
|
||||
Provides-Extra: lxml
|
||||
Requires-Dist: lxml; extra == 'lxml'
|
||||
Description-Content-Type: text/markdown
|
||||
|
||||
Beautiful Soup is a library that makes it easy to scrape information
|
||||
from web pages. It sits atop an HTML or XML parser, providing Pythonic
|
||||
idioms for iterating, searching, and modifying the parse tree.
|
||||
|
||||
# Quick start
|
||||
|
||||
```
|
||||
>>> from bs4 import BeautifulSoup
|
||||
>>> soup = BeautifulSoup("<p>Some<b>bad<i>HTML")
|
||||
>>> print(soup.prettify())
|
||||
<html>
|
||||
<body>
|
||||
<p>
|
||||
Some
|
||||
<b>
|
||||
bad
|
||||
<i>
|
||||
HTML
|
||||
</i>
|
||||
</b>
|
||||
</p>
|
||||
</body>
|
||||
</html>
|
||||
>>> soup.find(string="bad")
|
||||
'bad'
|
||||
>>> soup.i
|
||||
<i>HTML</i>
|
||||
#
|
||||
>>> soup = BeautifulSoup("<tag1>Some<tag2/>bad<tag3>XML", "xml")
|
||||
#
|
||||
>>> print(soup.prettify())
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<tag1>
|
||||
Some
|
||||
<tag2/>
|
||||
bad
|
||||
<tag3>
|
||||
XML
|
||||
</tag3>
|
||||
</tag1>
|
||||
```
|
||||
|
||||
To go beyond the basics, [comprehensive documentation is available](https://www.crummy.com/software/BeautifulSoup/bs4/doc/).
|
||||
|
||||
# Links
|
||||
|
||||
* [Homepage](https://www.crummy.com/software/BeautifulSoup/bs4/)
|
||||
* [Documentation](https://www.crummy.com/software/BeautifulSoup/bs4/doc/)
|
||||
* [Discussion group](https://groups.google.com/group/beautifulsoup/)
|
||||
* [Development](https://code.launchpad.net/beautifulsoup/)
|
||||
* [Bug tracker](https://bugs.launchpad.net/beautifulsoup/)
|
||||
* [Complete changelog](https://git.launchpad.net/beautifulsoup/tree/CHANGELOG)
|
||||
|
||||
# Note on Python 2 sunsetting
|
||||
|
||||
Beautiful Soup's support for Python 2 was discontinued on December 31,
|
||||
2020: one year after the sunset date for Python 2 itself. From this
|
||||
point onward, new Beautiful Soup development will exclusively target
|
||||
Python 3. The final release of Beautiful Soup 4 to support Python 2
|
||||
was 4.9.3.
|
||||
|
||||
# Supporting the project
|
||||
|
||||
If you use Beautiful Soup as part of your professional work, please consider a
|
||||
[Tidelift subscription](https://tidelift.com/subscription/pkg/pypi-beautifulsoup4?utm_source=pypi-beautifulsoup4&utm_medium=referral&utm_campaign=readme).
|
||||
This will support many of the free software projects your organization
|
||||
depends on, not just Beautiful Soup.
|
||||
|
||||
If you use Beautiful Soup for personal projects, the best way to say
|
||||
thank you is to read
|
||||
[Tool Safety](https://www.crummy.com/software/BeautifulSoup/zine/), a zine I
|
||||
wrote about what Beautiful Soup has taught me about software
|
||||
development.
|
||||
|
||||
# Building the documentation
|
||||
|
||||
The bs4/doc/ directory contains full documentation in Sphinx
|
||||
format. Run `make html` in that directory to create HTML
|
||||
documentation.
|
||||
|
||||
# Running the unit tests
|
||||
|
||||
Beautiful Soup supports unit test discovery using Pytest:
|
||||
|
||||
```
|
||||
$ pytest
|
||||
```
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
Wheel-Version: 1.0
|
||||
Generator: hatchling 1.27.0
|
||||
Root-Is-Purelib: true
|
||||
Tag: py3-none-any
|
||||
@@ -0,0 +1,49 @@
|
||||
Behold, mortal, the origins of Beautiful Soup...
|
||||
================================================
|
||||
|
||||
Leonard Richardson is the primary maintainer.
|
||||
|
||||
Aaron DeVore, Isaac Muse and Chris Papademetrious have made
|
||||
significant contributions to the code base.
|
||||
|
||||
Mark Pilgrim provided the encoding detection code that forms the base
|
||||
of UnicodeDammit.
|
||||
|
||||
Thomas Kluyver and Ezio Melotti finished the work of getting Beautiful
|
||||
Soup 4 working under Python 3.
|
||||
|
||||
Simon Willison wrote soupselect, which was used to make Beautiful Soup
|
||||
support CSS selectors. Isaac Muse wrote SoupSieve, which made it
|
||||
possible to _remove_ the CSS selector code from Beautiful Soup.
|
||||
|
||||
Sam Ruby helped with a lot of edge cases.
|
||||
|
||||
Jonathan Ellis was awarded the prestigious Beau Potage D'Or for his
|
||||
work in solving the nestable tags conundrum.
|
||||
|
||||
An incomplete list of people have contributed patches to Beautiful
|
||||
Soup:
|
||||
|
||||
Istvan Albert, Andrew Lin, Anthony Baxter, Oliver Beattie, Andrew
|
||||
Boyko, Tony Chang, Francisco Canas, "Delong", Zephyr Fang, Fuzzy,
|
||||
Roman Gaufman, Yoni Gilad, Richie Hindle, Toshihiro Kamiya, Peteris
|
||||
Krumins, Kent Johnson, Marek Kapolka, Andreas Kostyrka, Roel Kramer,
|
||||
Ben Last, Robert Leftwich, Stefaan Lippens, "liquider", Staffan
|
||||
Malmgren, Ksenia Marasanova, JP Moins, Adam Monsen, John Nagle, "Jon",
|
||||
Ed Oskiewicz, Martijn Peters, Greg Phillips, Giles Radford, Stefano
|
||||
Revera, Arthur Rudolph, Marko Samastur, James Salter, Jouni Seppänen,
|
||||
Alexander Schmolck, Tim Shirley, Geoffrey Sneddon, Ville Skyttä,
|
||||
"Vikas", Jens Svalgaard, Andy Theyers, Eric Weiser, Glyn Webster, John
|
||||
Wiseman, Paul Wright, Danny Yoo
|
||||
|
||||
An incomplete list of people who made suggestions or found bugs or
|
||||
found ways to break Beautiful Soup:
|
||||
|
||||
Hanno Böck, Matteo Bertini, Chris Curvey, Simon Cusack, Bruce Eckel,
|
||||
Matt Ernst, Michael Foord, Tom Harris, Bill de hOra, Donald Howes,
|
||||
Matt Patterson, Scott Roberts, Steve Strassmann, Mike Williams,
|
||||
warchild at redho dot com, Sami Kuisma, Carlos Rocha, Bob Hutchison,
|
||||
Joren Mc, Michal Migurski, John Kleven, Tim Heaney, Tripp Lilley, Ed
|
||||
Summers, Dennis Sutch, Chris Smith, Aaron Swartz, Stuart
|
||||
Turner, Greg Edwards, Kevin J Kalupson, Nikos Kouremenos, Artur de
|
||||
Sousa Rocha, Yichun Wei, Per Vognsen
|
||||
@@ -0,0 +1,31 @@
|
||||
Beautiful Soup is made available under the MIT license:
|
||||
|
||||
Copyright (c) Leonard Richardson
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
||||
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
Beautiful Soup incorporates code from the html5lib library, which is
|
||||
also made available under the MIT license. Copyright (c) James Graham
|
||||
and other contributors
|
||||
|
||||
Beautiful Soup has an optional dependency on the soupsieve library,
|
||||
which is also made available under the MIT license. Copyright (c)
|
||||
Isaac Muse
|
||||
+1179
File diff suppressed because it is too large.
Load diff
+80
@@ -0,0 +1,80 @@
|
||||
"""Helper functions for deprecation.
|
||||
|
||||
This interface is itself unstable and may change without warning. Do
|
||||
not use these functions yourself, even as a joke. The underscores are
|
||||
there for a reason. No support will be given.
|
||||
|
||||
In particular, most of this will go away without warning once
|
||||
Beautiful Soup drops support for Python 3.11, since Python 3.12
|
||||
defines a `@typing.deprecated()
|
||||
decorator. <https://peps.python.org/pep-0702/>`_
|
||||
"""
|
||||
|
||||
import functools
|
||||
import warnings
|
||||
|
||||
from typing import (
|
||||
Any,
|
||||
Callable,
|
||||
)
|
||||
|
||||
|
||||
def _deprecated_alias(old_name: str, new_name: str, version: str):
|
||||
"""Alias one attribute name to another for backward compatibility
|
||||
|
||||
:meta private:
|
||||
"""
|
||||
|
||||
@property # type:ignore
|
||||
def alias(self) -> Any:
|
||||
":meta private:"
|
||||
warnings.warn(
|
||||
f"Access to deprecated property {old_name}. (Replaced by {new_name}) -- Deprecated since version {version}.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
return getattr(self, new_name)
|
||||
|
||||
@alias.setter
|
||||
def alias(self, value: str) -> None:
|
||||
":meta private:"
|
||||
warnings.warn(
|
||||
f"Write to deprecated property {old_name}. (Replaced by {new_name}) -- Deprecated since version {version}.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
return setattr(self, new_name, value)
|
||||
|
||||
return alias
|
||||
|
||||
|
||||
def _deprecated_function_alias(
|
||||
old_name: str, new_name: str, version: str
|
||||
) -> Callable[[Any], Any]:
|
||||
def alias(self, *args: Any, **kwargs: Any) -> Any:
|
||||
":meta private:"
|
||||
warnings.warn(
|
||||
f"Call to deprecated method {old_name}. (Replaced by {new_name}) -- Deprecated since version {version}.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
return getattr(self, new_name)(*args, **kwargs)
|
||||
|
||||
return alias
|
||||
|
||||
|
||||
def _deprecated(replaced_by: str, version: str) -> Callable:
|
||||
def deprecate(func: Callable) -> Callable:
|
||||
@functools.wraps(func)
|
||||
def with_warning(*args: Any, **kwargs: Any) -> Any:
|
||||
":meta private:"
|
||||
warnings.warn(
|
||||
f"Call to deprecated method {func.__name__}. (Replaced by {replaced_by}) -- Deprecated since version {version}.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
return func(*args, **kwargs)
|
||||
|
||||
return with_warning
|
||||
|
||||
return deprecate
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
# Custom type aliases used throughout Beautiful Soup to improve readability.
|
||||
|
||||
# Notes on improvements to the type system in newer versions of Python
|
||||
# that can be used once Beautiful Soup drops support for older
|
||||
# versions:
|
||||
#
|
||||
# * ClassVar can be put on class variables now.
|
||||
# * In 3.10, x|y is an accepted shorthand for Union[x,y].
|
||||
# * In 3.10, TypeAlias gains capabilities that can be used to
|
||||
# improve the tree matching types (I don't remember what, exactly).
|
||||
# * In 3.9 it's possible to specialize the re.Match type,
|
||||
# e.g. re.Match[str]. In 3.8 there's a typing.re namespace for this,
|
||||
# but it's removed in 3.12, so to support the widest possible set of
|
||||
# versions I'm not using it.
|
||||
|
||||
from typing_extensions import (
|
||||
runtime_checkable,
|
||||
Protocol,
|
||||
TypeAlias,
|
||||
)
|
||||
from typing import (
|
||||
Any,
|
||||
Callable,
|
||||
Dict,
|
||||
IO,
|
||||
Iterable,
|
||||
Mapping,
|
||||
Optional,
|
||||
Pattern,
|
||||
TYPE_CHECKING,
|
||||
Union,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from bs4.element import (
|
||||
AttributeValueList,
|
||||
NamespacedAttribute,
|
||||
NavigableString,
|
||||
PageElement,
|
||||
ResultSet,
|
||||
Tag,
|
||||
)
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class _RegularExpressionProtocol(Protocol):
|
||||
"""A protocol object which can accept either Python's built-in
|
||||
`re.Pattern` objects, or the similar ``Regex`` objects defined by the
|
||||
third-party ``regex`` package.
|
||||
"""
|
||||
|
||||
def search(
|
||||
self, string: str, pos: int = ..., endpos: int = ...
|
||||
) -> Optional[Any]: ...
|
||||
|
||||
@property
|
||||
def pattern(self) -> str: ...
|
||||
|
||||
|
||||
# Aliases for markup in various stages of processing.
|
||||
#
|
||||
#: The rawest form of markup: either a string, bytestring, or an open filehandle.
|
||||
_IncomingMarkup: TypeAlias = Union[str, bytes, IO[str], IO[bytes]]
|
||||
|
||||
#: Markup that is in memory but has (potentially) yet to be converted
|
||||
#: to Unicode.
|
||||
_RawMarkup: TypeAlias = Union[str, bytes]
|
||||
|
||||
# Aliases for character encodings
|
||||
#
|
||||
|
||||
#: A data encoding.
|
||||
_Encoding: TypeAlias = str
|
||||
|
||||
#: One or more data encodings.
|
||||
_Encodings: TypeAlias = Iterable[_Encoding]
|
||||
|
||||
# Aliases for XML namespaces
|
||||
#
|
||||
|
||||
#: The prefix for an XML namespace.
|
||||
_NamespacePrefix: TypeAlias = str
|
||||
|
||||
#: The URL of an XML namespace
|
||||
_NamespaceURL: TypeAlias = str
|
||||
|
||||
#: A mapping of prefixes to namespace URLs.
|
||||
_NamespaceMapping: TypeAlias = Dict[_NamespacePrefix, _NamespaceURL]
|
||||
|
||||
#: A mapping of namespace URLs to prefixes
|
||||
_InvertedNamespaceMapping: TypeAlias = Dict[_NamespaceURL, _NamespacePrefix]
|
||||
|
||||
# Aliases for the attribute values associated with HTML/XML tags.
|
||||
#
|
||||
|
||||
#: The value associated with an HTML or XML attribute. This is the
|
||||
#: relatively unprocessed value Beautiful Soup expects to come from a
|
||||
#: `TreeBuilder`.
|
||||
_RawAttributeValue: TypeAlias = str
|
||||
|
||||
#: A dictionary of names to `_RawAttributeValue` objects. This is how
|
||||
#: Beautiful Soup expects a `TreeBuilder` to represent a tag's
|
||||
#: attribute values.
|
||||
_RawAttributeValues: TypeAlias = (
|
||||
"Mapping[Union[str, NamespacedAttribute], _RawAttributeValue]"
|
||||
)
|
||||
|
||||
#: An attribute value in its final form, as stored in the
|
||||
# `Tag` class, after it has been processed and (in some cases)
|
||||
# split into a list of strings.
|
||||
_AttributeValue: TypeAlias = Union[str, "AttributeValueList"]
|
||||
|
||||
#: A dictionary of names to :py:data:`_AttributeValue` objects. This is what
|
||||
#: a tag's attributes look like after processing.
|
||||
_AttributeValues: TypeAlias = Dict[str, _AttributeValue]
|
||||
|
||||
#: The methods that deal with turning :py:data:`_RawAttributeValue` into
|
||||
#: :py:data:`_AttributeValue` may be called several times, even after the values
|
||||
#: are already processed (e.g. when cloning a tag), so they need to
|
||||
#: be able to acommodate both possibilities.
|
||||
_RawOrProcessedAttributeValues: TypeAlias = Union[_RawAttributeValues, _AttributeValues]
|
||||
|
||||
#: A number of tree manipulation methods can take either a `PageElement` or a
|
||||
#: normal Python string (which will be converted to a `NavigableString`).
|
||||
_InsertableElement: TypeAlias = Union["PageElement", str]
|
||||
|
||||
# Aliases to represent the many possibilities for matching bits of a
|
||||
# parse tree.
|
||||
#
|
||||
# This is very complicated because we're applying a formal type system
|
||||
# to some very DWIM code. The types we end up with will be the types
|
||||
# of the arguments to the SoupStrainer constructor and (more
|
||||
# familiarly to Beautiful Soup users) the find* methods.
|
||||
|
||||
#: A function that takes a PageElement and returns a yes-or-no answer.
|
||||
_PageElementMatchFunction: TypeAlias = Callable[["PageElement"], bool]
|
||||
|
||||
#: A function that takes the raw parsed ingredients of a markup tag
|
||||
#: and returns a yes-or-no answer.
|
||||
# Not necessary at the moment.
|
||||
# _AllowTagCreationFunction:TypeAlias = Callable[[Optional[str], str, Optional[_RawAttributeValues]], bool]
|
||||
|
||||
#: A function that takes the raw parsed ingredients of a markup string node
|
||||
#: and returns a yes-or-no answer.
|
||||
# Not necessary at the moment.
|
||||
# _AllowStringCreationFunction:TypeAlias = Callable[[Optional[str]], bool]
|
||||
|
||||
#: A function that takes a `Tag` and returns a yes-or-no answer.
|
||||
#: A `TagNameMatchRule` expects this kind of function, if you're
|
||||
#: going to pass it a function.
|
||||
_TagMatchFunction: TypeAlias = Callable[["Tag"], bool]
|
||||
|
||||
#: A function that takes a string (or None) and returns a yes-or-no
|
||||
#: answer. An `AttributeValueMatchRule` expects this kind of function, if
|
||||
#: you're going to pass it a function.
|
||||
_NullableStringMatchFunction: TypeAlias = Callable[[Optional[str]], bool]
|
||||
|
||||
#: A function that takes a string and returns a yes-or-no answer. A
|
||||
# `StringMatchRule` expects this kind of function, if you're going to
|
||||
# pass it a function.
|
||||
_StringMatchFunction: TypeAlias = Callable[[str], bool]
|
||||
|
||||
#: Either a tag name, an attribute value or a string can be matched
|
||||
#: against a string, bytestring, regular expression, or a boolean.
|
||||
_BaseStrainable: TypeAlias = Union[str, bytes, Pattern[str], bool]
|
||||
|
||||
#: A tag can be matched either with the `_BaseStrainable` options, or
|
||||
#: using a function that takes the `Tag` as its sole argument.
|
||||
_BaseStrainableElement: TypeAlias = Union[_BaseStrainable, _TagMatchFunction]
|
||||
|
||||
#: A tag's attribute value can be matched either with the
|
||||
#: `_BaseStrainable` options, or using a function that takes that
|
||||
#: value as its sole argument.
|
||||
_BaseStrainableAttribute: TypeAlias = Union[_BaseStrainable, _NullableStringMatchFunction]
|
||||
|
||||
#: A tag can be matched using either a single criterion or a list of
|
||||
#: criteria.
|
||||
_StrainableElement: TypeAlias = Union[
|
||||
_BaseStrainableElement, Iterable[_BaseStrainableElement]
|
||||
]
|
||||
|
||||
#: An attribute value can be matched using either a single criterion
|
||||
#: or a list of criteria.
|
||||
_StrainableAttribute: TypeAlias = Union[
|
||||
_BaseStrainableAttribute, Iterable[_BaseStrainableAttribute]
|
||||
]
|
||||
|
||||
#: An string can be matched using the same techniques as
|
||||
#: an attribute value.
|
||||
_StrainableString: TypeAlias = _StrainableAttribute
|
||||
|
||||
#: A dictionary may be used to match against multiple attribute vlaues at once.
|
||||
_StrainableAttributes: TypeAlias = Dict[str, _StrainableAttribute]
|
||||
|
||||
#: Many Beautiful soup methods return a PageElement or an ResultSet of
|
||||
#: PageElements. A PageElement is either a Tag or a NavigableString.
|
||||
#: These convenience aliases make it easier for IDE users to see which methods
|
||||
#: are available on the objects they're dealing with.
|
||||
_OneElement: TypeAlias = Union["PageElement", "Tag", "NavigableString"]
|
||||
_AtMostOneElement: TypeAlias = Optional[_OneElement]
|
||||
_AtMostOneTag: TypeAlias = Optional["Tag"]
|
||||
_AtMostOneNavigableString: TypeAlias = Optional["NavigableString"]
|
||||
_QueryResults: TypeAlias = "ResultSet[_OneElement]"
|
||||
_SomeTags: TypeAlias = "ResultSet[Tag]"
|
||||
_SomeNavigableStrings: TypeAlias = "ResultSet[NavigableString]"
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
"""Define some custom warnings."""
|
||||
|
||||
|
||||
class GuessedAtParserWarning(UserWarning):
|
||||
"""The warning issued when BeautifulSoup has to guess what parser to
|
||||
use -- probably because no parser was specified in the constructor.
|
||||
"""
|
||||
|
||||
MESSAGE: str = """No parser was explicitly specified, so I'm using the best available %(markup_type)s parser for this system ("%(parser)s"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.
|
||||
|
||||
The code that caused this warning is on line %(line_number)s of the file %(filename)s. To get rid of this warning, pass the additional argument 'features="%(parser)s"' to the BeautifulSoup constructor.
|
||||
"""
|
||||
|
||||
|
||||
class UnusualUsageWarning(UserWarning):
|
||||
"""A superclass for warnings issued when Beautiful Soup sees
|
||||
something that is typically the result of a mistake in the calling
|
||||
code, but might be intentional on the part of the user. If it is
|
||||
in fact intentional, you can filter the individual warning class
|
||||
to get rid of the warning. If you don't like Beautiful Soup
|
||||
second-guessing what you are doing, you can filter the
|
||||
UnusualUsageWarningclass itself and get rid of these entirely.
|
||||
"""
|
||||
|
||||
|
||||
class MarkupResemblesLocatorWarning(UnusualUsageWarning):
|
||||
"""The warning issued when BeautifulSoup is given 'markup' that
|
||||
actually looks like a resource locator -- a URL or a path to a file
|
||||
on disk.
|
||||
"""
|
||||
|
||||
#: :meta private:
|
||||
GENERIC_MESSAGE: str = """
|
||||
|
||||
However, if you want to parse some data that happens to look like a %(what)s, then nothing has gone wrong: you are using Beautiful Soup correctly, and this warning is spurious and can be filtered. To make this warning go away, run this code before calling the BeautifulSoup constructor:
|
||||
|
||||
from bs4 import MarkupResemblesLocatorWarning
|
||||
import warnings
|
||||
|
||||
warnings.filterwarnings("ignore", category=MarkupResemblesLocatorWarning)
|
||||
"""
|
||||
|
||||
URL_MESSAGE: str = (
|
||||
"""The input passed in on this line looks more like a URL than HTML or XML.
|
||||
|
||||
If you meant to use Beautiful Soup to parse the web page found at a certain URL, then something has gone wrong. You should use an Python package like 'requests' to fetch the content behind the URL. Once you have the content as a string, you can feed that string into Beautiful Soup."""
|
||||
+ GENERIC_MESSAGE
|
||||
)
|
||||
|
||||
FILENAME_MESSAGE: str = (
|
||||
"""The input passed in on this line looks more like a filename than HTML or XML.
|
||||
|
||||
If you meant to use Beautiful Soup to parse the contents of a file on disk, then something has gone wrong. You should open the file first, using code like this:
|
||||
|
||||
filehandle = open(your filename)
|
||||
|
||||
You can then feed the open filehandle into Beautiful Soup instead of using the filename."""
|
||||
+ GENERIC_MESSAGE
|
||||
)
|
||||
|
||||
|
||||
class AttributeResemblesVariableWarning(UnusualUsageWarning, SyntaxWarning):
|
||||
"""The warning issued when Beautiful Soup suspects a provided
|
||||
attribute name may actually be the misspelled name of a Beautiful
|
||||
Soup variable. Generally speaking, this is only used in cases like
|
||||
"_class" where it's very unlikely the user would be referencing an
|
||||
XML attribute with that name.
|
||||
"""
|
||||
|
||||
MESSAGE: str = """%(original)r is an unusual attribute name and is a common misspelling for %(autocorrect)r.
|
||||
|
||||
If you meant %(autocorrect)r, change your code to use it, and this warning will go away.
|
||||
|
||||
If you really did mean to check the %(original)r attribute, this warning is spurious and can be filtered. To make it go away, run this code before creating your BeautifulSoup object:
|
||||
|
||||
from bs4 import AttributeResemblesVariableWarning
|
||||
import warnings
|
||||
|
||||
warnings.filterwarnings("ignore", category=AttributeResemblesVariableWarning)
|
||||
"""
|
||||
|
||||
|
||||
class XMLParsedAsHTMLWarning(UnusualUsageWarning):
|
||||
"""The warning issued when an HTML parser is used to parse
|
||||
XML that is not (as far as we can tell) XHTML.
|
||||
"""
|
||||
|
||||
MESSAGE: str = """It looks like you're using an HTML parser to parse an XML document.
|
||||
|
||||
Assuming this really is an XML document, what you're doing might work, but you should know that using an XML parser will be more reliable. To parse this document as XML, make sure you have the Python package 'lxml' installed, and pass the keyword argument `features="xml"` into the BeautifulSoup constructor.
|
||||
|
||||
If you want or need to use an HTML parser on this document, you can make this warning go away by filtering it. To do that, run this code before calling the BeautifulSoup constructor:
|
||||
|
||||
from bs4 import XMLParsedAsHTMLWarning
|
||||
import warnings
|
||||
|
||||
warnings.filterwarnings("ignore", category=XMLParsedAsHTMLWarning)
|
||||
"""
|
||||
+848
@@ -0,0 +1,848 @@
|
||||
from __future__ import annotations
|
||||
|
||||
# Use of this source code is governed by the MIT license.
|
||||
__license__ = "MIT"
|
||||
|
||||
from collections import defaultdict
|
||||
import re
|
||||
from types import ModuleType
|
||||
from typing import (
|
||||
Any,
|
||||
cast,
|
||||
Dict,
|
||||
Iterable,
|
||||
List,
|
||||
Optional,
|
||||
Pattern,
|
||||
Set,
|
||||
Tuple,
|
||||
Type,
|
||||
TYPE_CHECKING,
|
||||
)
|
||||
import warnings
|
||||
import sys
|
||||
from bs4.element import (
|
||||
AttributeDict,
|
||||
AttributeValueList,
|
||||
CharsetMetaAttributeValue,
|
||||
ContentMetaAttributeValue,
|
||||
RubyParenthesisString,
|
||||
RubyTextString,
|
||||
Stylesheet,
|
||||
Script,
|
||||
TemplateString,
|
||||
nonwhitespace_re,
|
||||
)
|
||||
|
||||
# Exceptions were moved to their own module in 4.13. Import here for
|
||||
# backwards compatibility.
|
||||
from bs4.exceptions import ParserRejectedMarkup
|
||||
|
||||
from bs4._typing import (
|
||||
_AttributeValues,
|
||||
_RawAttributeValue,
|
||||
)
|
||||
|
||||
from bs4._warnings import XMLParsedAsHTMLWarning
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from bs4 import BeautifulSoup
|
||||
from bs4.element import (
|
||||
NavigableString,
|
||||
Tag,
|
||||
)
|
||||
from bs4._typing import (
|
||||
_AttributeValue,
|
||||
_Encoding,
|
||||
_Encodings,
|
||||
_RawOrProcessedAttributeValues,
|
||||
_RawMarkup,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"HTMLTreeBuilder",
|
||||
"SAXTreeBuilder",
|
||||
"TreeBuilder",
|
||||
"TreeBuilderRegistry",
|
||||
]
|
||||
|
||||
# Some useful features for a TreeBuilder to have.
|
||||
FAST = "fast"
|
||||
PERMISSIVE = "permissive"
|
||||
STRICT = "strict"
|
||||
XML = "xml"
|
||||
HTML = "html"
|
||||
HTML_5 = "html5"
|
||||
|
||||
__all__ = [
|
||||
"TreeBuilderRegistry",
|
||||
"TreeBuilder",
|
||||
"HTMLTreeBuilder",
|
||||
"DetectsXMLParsedAsHTML",
|
||||
|
||||
"ParserRejectedMarkup", # backwards compatibility only as of 4.13.0
|
||||
]
|
||||
|
||||
class TreeBuilderRegistry(object):
|
||||
"""A way of looking up TreeBuilder subclasses by their name or by desired
|
||||
features.
|
||||
"""
|
||||
|
||||
builders_for_feature: Dict[str, List[Type[TreeBuilder]]]
|
||||
builders: List[Type[TreeBuilder]]
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.builders_for_feature = defaultdict(list)
|
||||
self.builders = []
|
||||
|
||||
def register(self, treebuilder_class: type[TreeBuilder]) -> None:
|
||||
"""Register a treebuilder based on its advertised features.
|
||||
|
||||
:param treebuilder_class: A subclass of `TreeBuilder`. its
|
||||
`TreeBuilder.features` attribute should list its features.
|
||||
"""
|
||||
for feature in treebuilder_class.features:
|
||||
self.builders_for_feature[feature].insert(0, treebuilder_class)
|
||||
self.builders.insert(0, treebuilder_class)
|
||||
|
||||
def lookup(self, *features: str) -> Optional[Type[TreeBuilder]]:
|
||||
"""Look up a TreeBuilder subclass with the desired features.
|
||||
|
||||
:param features: A list of features to look for. If none are
|
||||
provided, the most recently registered TreeBuilder subclass
|
||||
will be used.
|
||||
:return: A TreeBuilder subclass, or None if there's no
|
||||
registered subclass with all the requested features.
|
||||
"""
|
||||
if len(self.builders) == 0:
|
||||
# There are no builders at all.
|
||||
return None
|
||||
|
||||
if len(features) == 0:
|
||||
# They didn't ask for any features. Give them the most
|
||||
# recently registered builder.
|
||||
return self.builders[0]
|
||||
|
||||
# Go down the list of features in order, and eliminate any builders
|
||||
# that don't match every feature.
|
||||
feature_list = list(features)
|
||||
feature_list.reverse()
|
||||
candidates = None
|
||||
candidate_set = None
|
||||
while len(feature_list) > 0:
|
||||
feature = feature_list.pop()
|
||||
we_have_the_feature = self.builders_for_feature.get(feature, [])
|
||||
if len(we_have_the_feature) > 0:
|
||||
if candidates is None:
|
||||
candidates = we_have_the_feature
|
||||
candidate_set = set(candidates)
|
||||
elif candidate_set is not None:
|
||||
# Eliminate any candidates that don't have this feature.
|
||||
candidate_set = candidate_set.intersection(set(we_have_the_feature))
|
||||
|
||||
# The only valid candidates are the ones in candidate_set.
|
||||
# Go through the original list of candidates and pick the first one
|
||||
# that's in candidate_set.
|
||||
if candidate_set is None or candidates is None:
|
||||
return None
|
||||
for candidate in candidates:
|
||||
if candidate in candidate_set:
|
||||
return candidate
|
||||
return None
|
||||
|
||||
|
||||
#: The `BeautifulSoup` constructor will take a list of features
|
||||
#: and use it to look up `TreeBuilder` classes in this registry.
|
||||
builder_registry: TreeBuilderRegistry = TreeBuilderRegistry()
|
||||
|
||||
|
||||
class TreeBuilder(object):
|
||||
"""Turn a textual document into a Beautiful Soup object tree.
|
||||
|
||||
This is an abstract superclass which smooths out the behavior of
|
||||
different parser libraries into a single, unified interface.
|
||||
|
||||
:param multi_valued_attributes: If this is set to None, the
|
||||
TreeBuilder will not turn any values for attributes like
|
||||
'class' into lists. Setting this to a dictionary will
|
||||
customize this behavior; look at :py:attr:`bs4.builder.HTMLTreeBuilder.DEFAULT_CDATA_LIST_ATTRIBUTES`
|
||||
for an example.
|
||||
|
||||
Internally, these are called "CDATA list attributes", but that
|
||||
probably doesn't make sense to an end-user, so the argument name
|
||||
is ``multi_valued_attributes``.
|
||||
|
||||
:param preserve_whitespace_tags: A set of tags to treat
|
||||
the way <pre> tags are treated in HTML. Tags in this set
|
||||
are immune from pretty-printing; their contents will always be
|
||||
output as-is.
|
||||
|
||||
:param string_containers: A dictionary mapping tag names to
|
||||
the classes that should be instantiated to contain the textual
|
||||
contents of those tags. The default is to use NavigableString
|
||||
for every tag, no matter what the name. You can override the
|
||||
default by changing :py:attr:`DEFAULT_STRING_CONTAINERS`.
|
||||
|
||||
:param store_line_numbers: If the parser keeps track of the line
|
||||
numbers and positions of the original markup, that information
|
||||
will, by default, be stored in each corresponding
|
||||
:py:class:`bs4.element.Tag` object. You can turn this off by
|
||||
passing store_line_numbers=False; then Tag.sourcepos and
|
||||
Tag.sourceline will always be None. If the parser you're using
|
||||
doesn't keep track of this information, then store_line_numbers
|
||||
is irrelevant.
|
||||
|
||||
:param attribute_dict_class: The value of a multi-valued attribute
|
||||
(such as HTML's 'class') willl be stored in an instance of this
|
||||
class. The default is Beautiful Soup's built-in
|
||||
`AttributeValueList`, which is a normal Python list, and you
|
||||
will probably never need to change it.
|
||||
"""
|
||||
|
||||
USE_DEFAULT: Any = object() #: :meta private:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
multi_valued_attributes: Dict[str, Set[str]] = USE_DEFAULT,
|
||||
preserve_whitespace_tags: Set[str] = USE_DEFAULT,
|
||||
store_line_numbers: bool = USE_DEFAULT,
|
||||
string_containers: Dict[str, Type[NavigableString]] = USE_DEFAULT,
|
||||
empty_element_tags: Set[str] = USE_DEFAULT,
|
||||
attribute_dict_class: Type[AttributeDict] = AttributeDict,
|
||||
attribute_value_list_class: Type[AttributeValueList] = AttributeValueList,
|
||||
):
|
||||
self.soup = None
|
||||
if multi_valued_attributes is self.USE_DEFAULT:
|
||||
multi_valued_attributes = self.DEFAULT_CDATA_LIST_ATTRIBUTES
|
||||
self.cdata_list_attributes = multi_valued_attributes
|
||||
if preserve_whitespace_tags is self.USE_DEFAULT:
|
||||
preserve_whitespace_tags = self.DEFAULT_PRESERVE_WHITESPACE_TAGS
|
||||
self.preserve_whitespace_tags = preserve_whitespace_tags
|
||||
if empty_element_tags is self.USE_DEFAULT:
|
||||
self.empty_element_tags = self.DEFAULT_EMPTY_ELEMENT_TAGS
|
||||
else:
|
||||
self.empty_element_tags = empty_element_tags
|
||||
# TODO: store_line_numbers is probably irrelevant now that
|
||||
# the behavior of sourceline and sourcepos has been made consistent
|
||||
# everywhere.
|
||||
if store_line_numbers == self.USE_DEFAULT:
|
||||
store_line_numbers = self.TRACKS_LINE_NUMBERS
|
||||
self.store_line_numbers = store_line_numbers
|
||||
if string_containers == self.USE_DEFAULT:
|
||||
string_containers = self.DEFAULT_STRING_CONTAINERS
|
||||
self.string_containers = string_containers
|
||||
self.attribute_dict_class = attribute_dict_class
|
||||
self.attribute_value_list_class = attribute_value_list_class
|
||||
|
||||
NAME: str = "[Unknown tree builder]"
|
||||
ALTERNATE_NAMES: Iterable[str] = []
|
||||
features: Iterable[str] = []
|
||||
|
||||
is_xml: bool = False
|
||||
picklable: bool = False
|
||||
|
||||
soup: Optional[BeautifulSoup] #: :meta private:
|
||||
|
||||
#: A tag will be considered an empty-element
|
||||
#: tag when and only when it has no contents.
|
||||
empty_element_tags: Optional[Set[str]] = None #: :meta private:
|
||||
cdata_list_attributes: Dict[str, Set[str]] #: :meta private:
|
||||
preserve_whitespace_tags: Set[str] #: :meta private:
|
||||
string_containers: Dict[str, Type[NavigableString]] #: :meta private:
|
||||
tracks_line_numbers: bool #: :meta private:
|
||||
|
||||
#: A value for these tag/attribute combinations is a space- or
|
||||
#: comma-separated list of CDATA, rather than a single CDATA.
|
||||
DEFAULT_CDATA_LIST_ATTRIBUTES: Dict[str, Set[str]] = defaultdict(set)
|
||||
|
||||
#: Whitespace should be preserved inside these tags.
|
||||
DEFAULT_PRESERVE_WHITESPACE_TAGS: Set[str] = set()
|
||||
|
||||
#: The textual contents of tags with these names should be
|
||||
#: instantiated with some class other than `bs4.element.NavigableString`.
|
||||
DEFAULT_STRING_CONTAINERS: Dict[str, Type[bs4.element.NavigableString]] = {} # type:ignore
|
||||
|
||||
#: By default, tags are treated as empty-element tags if they have
|
||||
#: no contents--that is, using XML rules. HTMLTreeBuilder
|
||||
#: defines a different set of DEFAULT_EMPTY_ELEMENT_TAGS based on the
|
||||
#: HTML 4 and HTML5 standards.
|
||||
DEFAULT_EMPTY_ELEMENT_TAGS: Optional[Set[str]] = None
|
||||
|
||||
#: Most parsers don't keep track of line numbers.
|
||||
TRACKS_LINE_NUMBERS: bool = False
|
||||
|
||||
def initialize_soup(self, soup: BeautifulSoup) -> None:
|
||||
"""The BeautifulSoup object has been initialized and is now
|
||||
being associated with the TreeBuilder.
|
||||
|
||||
:param soup: A BeautifulSoup object.
|
||||
"""
|
||||
self.soup = soup
|
||||
|
||||
def reset(self) -> None:
|
||||
"""Do any work necessary to reset the underlying parser
|
||||
for a new document.
|
||||
|
||||
By default, this does nothing.
|
||||
"""
|
||||
pass
|
||||
|
||||
def can_be_empty_element(self, tag_name: str) -> bool:
|
||||
"""Might a tag with this name be an empty-element tag?
|
||||
|
||||
The final markup may or may not actually present this tag as
|
||||
self-closing.
|
||||
|
||||
For instance: an HTMLBuilder does not consider a <p> tag to be
|
||||
an empty-element tag (it's not in
|
||||
HTMLBuilder.empty_element_tags). This means an empty <p> tag
|
||||
will be presented as "<p></p>", not "<p/>" or "<p>".
|
||||
|
||||
The default implementation has no opinion about which tags are
|
||||
empty-element tags, so a tag will be presented as an
|
||||
empty-element tag if and only if it has no children.
|
||||
"<foo></foo>" will become "<foo/>", and "<foo>bar</foo>" will
|
||||
be left alone.
|
||||
|
||||
:param tag_name: The name of a markup tag.
|
||||
"""
|
||||
if self.empty_element_tags is None:
|
||||
return True
|
||||
return tag_name in self.empty_element_tags
|
||||
|
||||
def feed(self, markup: _RawMarkup) -> None:
|
||||
"""Run incoming markup through some parsing process."""
|
||||
raise NotImplementedError()
|
||||
|
||||
def prepare_markup(
|
||||
self,
|
||||
markup: _RawMarkup,
|
||||
user_specified_encoding: Optional[_Encoding] = None,
|
||||
document_declared_encoding: Optional[_Encoding] = None,
|
||||
exclude_encodings: Optional[_Encodings] = None,
|
||||
) -> Iterable[Tuple[_RawMarkup, Optional[_Encoding], Optional[_Encoding], bool]]:
|
||||
"""Run any preliminary steps necessary to make incoming markup
|
||||
acceptable to the parser.
|
||||
|
||||
:param markup: The markup that's about to be parsed.
|
||||
:param user_specified_encoding: The user asked to try this encoding
|
||||
to convert the markup into a Unicode string.
|
||||
:param document_declared_encoding: The markup itself claims to be
|
||||
in this encoding. NOTE: This argument is not used by the
|
||||
calling code and can probably be removed.
|
||||
:param exclude_encodings: The user asked *not* to try any of
|
||||
these encodings.
|
||||
|
||||
:yield: A series of 4-tuples: (markup, encoding, declared encoding,
|
||||
has undergone character replacement)
|
||||
|
||||
Each 4-tuple represents a strategy that the parser can try
|
||||
to convert the document to Unicode and parse it. Each
|
||||
strategy will be tried in turn.
|
||||
|
||||
By default, the only strategy is to parse the markup
|
||||
as-is. See `LXMLTreeBuilderForXML` and
|
||||
`HTMLParserTreeBuilder` for implementations that take into
|
||||
account the quirks of particular parsers.
|
||||
|
||||
:meta private:
|
||||
|
||||
"""
|
||||
yield markup, None, None, False
|
||||
|
||||
def test_fragment_to_document(self, fragment: str) -> str:
|
||||
"""Wrap an HTML fragment to make it look like a document.
|
||||
|
||||
Different parsers do this differently. For instance, lxml
|
||||
introduces an empty <head> tag, and html5lib
|
||||
doesn't. Abstracting this away lets us write simple tests
|
||||
which run HTML fragments through the parser and compare the
|
||||
results against other HTML fragments.
|
||||
|
||||
This method should not be used outside of unit tests.
|
||||
|
||||
:param fragment: A fragment of HTML.
|
||||
:return: A full HTML document.
|
||||
:meta private:
|
||||
"""
|
||||
return fragment
|
||||
|
||||
def set_up_substitutions(self, tag: Tag) -> bool:
|
||||
"""Set up any substitutions that will need to be performed on
|
||||
a `Tag` when it's output as a string.
|
||||
|
||||
By default, this does nothing. See `HTMLTreeBuilder` for a
|
||||
case where this is used.
|
||||
|
||||
:return: Whether or not a substitution was performed.
|
||||
:meta private:
|
||||
"""
|
||||
return False
|
||||
|
||||
def _replace_cdata_list_attribute_values(
|
||||
self, tag_name: str, attrs: _RawOrProcessedAttributeValues
|
||||
) -> _AttributeValues:
|
||||
"""When an attribute value is associated with a tag that can
|
||||
have multiple values for that attribute, convert the string
|
||||
value to a list of strings.
|
||||
|
||||
Basically, replaces class="foo bar" with class=["foo", "bar"]
|
||||
|
||||
NOTE: This method modifies its input in place.
|
||||
|
||||
:param tag_name: The name of a tag.
|
||||
:param attrs: A dictionary containing the tag's attributes.
|
||||
Any appropriate attribute values will be modified in place.
|
||||
:return: The modified dictionary that was originally passed in.
|
||||
"""
|
||||
|
||||
# First, cast the attrs dict to _AttributeValues. This might
|
||||
# not be accurate yet, but it will be by the time this method
|
||||
# returns.
|
||||
modified_attrs = cast(_AttributeValues, attrs)
|
||||
if not modified_attrs or not self.cdata_list_attributes:
|
||||
# Nothing to do.
|
||||
return modified_attrs
|
||||
|
||||
# There is at least a possibility that we need to modify one of
|
||||
# the attribute values.
|
||||
universal: Set[str] = self.cdata_list_attributes.get("*", set())
|
||||
tag_specific = self.cdata_list_attributes.get(tag_name.lower(), None)
|
||||
for attr in list(modified_attrs.keys()):
|
||||
modified_value: _AttributeValue
|
||||
if attr in universal or (tag_specific and attr in tag_specific):
|
||||
# We have a "class"-type attribute whose string
|
||||
# value is a whitespace-separated list of
|
||||
# values. Split it into a list.
|
||||
original_value: _AttributeValue = modified_attrs[attr]
|
||||
if isinstance(original_value, _RawAttributeValue):
|
||||
# This is a _RawAttributeValue (a string) that
|
||||
# needs to be split and converted to a
|
||||
# AttributeValueList so it can be an
|
||||
# _AttributeValue.
|
||||
modified_value = self.attribute_value_list_class(
|
||||
nonwhitespace_re.findall(original_value)
|
||||
)
|
||||
else:
|
||||
# html5lib calls setAttributes twice for the
|
||||
# same tag when rearranging the parse tree. On
|
||||
# the second call the attribute value here is
|
||||
# already a list. This can also happen when a
|
||||
# Tag object is cloned. If this happens, leave
|
||||
# the value alone rather than trying to split
|
||||
# it again.
|
||||
modified_value = original_value
|
||||
modified_attrs[attr] = modified_value
|
||||
return modified_attrs
|
||||
|
||||
|
||||
class SAXTreeBuilder(TreeBuilder):
|
||||
"""A Beautiful Soup treebuilder that listens for SAX events.
|
||||
|
||||
This is not currently used for anything, and it will be removed
|
||||
soon. It was a good idea, but it wasn't properly integrated into the
|
||||
rest of Beautiful Soup, so there have been long stretches where it
|
||||
hasn't worked properly.
|
||||
"""
|
||||
|
||||
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
||||
warnings.warn(
|
||||
"The SAXTreeBuilder class was deprecated in 4.13.0 and will be removed soon thereafter. It is completely untested and probably doesn't work; do not use it.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
super(SAXTreeBuilder, self).__init__(*args, **kwargs)
|
||||
|
||||
def feed(self, markup: _RawMarkup) -> None:
|
||||
raise NotImplementedError()
|
||||
|
||||
def close(self) -> None:
|
||||
pass
|
||||
|
||||
def startElement(self, name: str, attrs: Dict[str, str]) -> None:
|
||||
attrs = AttributeDict((key[1], value) for key, value in list(attrs.items()))
|
||||
# print("Start %s, %r" % (name, attrs))
|
||||
assert self.soup is not None
|
||||
self.soup.handle_starttag(name, None, None, attrs)
|
||||
|
||||
def endElement(self, name: str) -> None:
|
||||
# print("End %s" % name)
|
||||
assert self.soup is not None
|
||||
self.soup.handle_endtag(name)
|
||||
|
||||
def startElementNS(
|
||||
self, nsTuple: Tuple[str, str], nodeName: str, attrs: Dict[str, str]
|
||||
) -> None:
|
||||
# Throw away (ns, nodeName) for now.
|
||||
self.startElement(nodeName, attrs)
|
||||
|
||||
def endElementNS(self, nsTuple: Tuple[str, str], nodeName: str) -> None:
|
||||
# Throw away (ns, nodeName) for now.
|
||||
self.endElement(nodeName)
|
||||
# handler.endElementNS((ns, node.nodeName), node.nodeName)
|
||||
|
||||
def startPrefixMapping(self, prefix: str, nodeValue: str) -> None:
|
||||
# Ignore the prefix for now.
|
||||
pass
|
||||
|
||||
def endPrefixMapping(self, prefix: str) -> None:
|
||||
# Ignore the prefix for now.
|
||||
# handler.endPrefixMapping(prefix)
|
||||
pass
|
||||
|
||||
def characters(self, content: str) -> None:
|
||||
assert self.soup is not None
|
||||
self.soup.handle_data(content)
|
||||
|
||||
def startDocument(self) -> None:
|
||||
pass
|
||||
|
||||
def endDocument(self) -> None:
|
||||
pass
|
||||
|
||||
|
||||
class HTMLTreeBuilder(TreeBuilder):
|
||||
"""This TreeBuilder knows facts about HTML, such as which tags are treated
|
||||
specially by the HTML standard.
|
||||
"""
|
||||
|
||||
#: Some HTML tags are defined as having no contents. Beautiful Soup
|
||||
#: treats these specially.
|
||||
DEFAULT_EMPTY_ELEMENT_TAGS: Optional[Set[str]] = set(
|
||||
[
|
||||
# These are from HTML5.
|
||||
"area",
|
||||
"base",
|
||||
"br",
|
||||
"col",
|
||||
"embed",
|
||||
"hr",
|
||||
"img",
|
||||
"input",
|
||||
"keygen",
|
||||
"link",
|
||||
"menuitem",
|
||||
"meta",
|
||||
"param",
|
||||
"source",
|
||||
"track",
|
||||
"wbr",
|
||||
# These are from earlier versions of HTML and are removed in HTML5.
|
||||
"basefont",
|
||||
"bgsound",
|
||||
"command",
|
||||
"frame",
|
||||
"image",
|
||||
"isindex",
|
||||
"nextid",
|
||||
"spacer",
|
||||
]
|
||||
)
|
||||
|
||||
#: The HTML standard defines these tags as block-level elements. Beautiful
|
||||
#: Soup does not treat these elements differently from other elements,
|
||||
#: but it may do so eventually, and this information is available if
|
||||
#: you need to use it.
|
||||
DEFAULT_BLOCK_ELEMENTS: Set[str] = set(
|
||||
[
|
||||
"address",
|
||||
"article",
|
||||
"aside",
|
||||
"blockquote",
|
||||
"canvas",
|
||||
"dd",
|
||||
"div",
|
||||
"dl",
|
||||
"dt",
|
||||
"fieldset",
|
||||
"figcaption",
|
||||
"figure",
|
||||
"footer",
|
||||
"form",
|
||||
"h1",
|
||||
"h2",
|
||||
"h3",
|
||||
"h4",
|
||||
"h5",
|
||||
"h6",
|
||||
"header",
|
||||
"hr",
|
||||
"li",
|
||||
"main",
|
||||
"nav",
|
||||
"noscript",
|
||||
"ol",
|
||||
"output",
|
||||
"p",
|
||||
"pre",
|
||||
"section",
|
||||
"table",
|
||||
"tfoot",
|
||||
"ul",
|
||||
"video",
|
||||
]
|
||||
)
|
||||
|
||||
#: These HTML tags need special treatment so they can be
|
||||
#: represented by a string class other than `bs4.element.NavigableString`.
|
||||
#:
|
||||
#: For some of these tags, it's because the HTML standard defines
|
||||
#: an unusual content model for them. I made this list by going
|
||||
#: through the HTML spec
|
||||
#: (https://html.spec.whatwg.org/#metadata-content) and looking for
|
||||
#: "metadata content" elements that can contain strings.
|
||||
#:
|
||||
#: The Ruby tags (<rt> and <rp>) are here despite being normal
|
||||
#: "phrasing content" tags, because the content they contain is
|
||||
#: qualitatively different from other text in the document, and it
|
||||
#: can be useful to be able to distinguish it.
|
||||
#:
|
||||
#: TODO: Arguably <noscript> could go here but it seems
|
||||
#: qualitatively different from the other tags.
|
||||
DEFAULT_STRING_CONTAINERS: Dict[str, Type[bs4.element.NavigableString]] = { # type:ignore
|
||||
"rt": RubyTextString,
|
||||
"rp": RubyParenthesisString,
|
||||
"style": Stylesheet,
|
||||
"script": Script,
|
||||
"template": TemplateString,
|
||||
}
|
||||
|
||||
#: The HTML standard defines these attributes as containing a
|
||||
#: space-separated list of values, not a single value. That is,
|
||||
#: class="foo bar" means that the 'class' attribute has two values,
|
||||
#: 'foo' and 'bar', not the single value 'foo bar'. When we
|
||||
#: encounter one of these attributes, we will parse its value into
|
||||
#: a list of values if possible. Upon output, the list will be
|
||||
#: converted back into a string.
|
||||
DEFAULT_CDATA_LIST_ATTRIBUTES: Dict[str, Set[str]] = {
|
||||
"*": {"class", "accesskey", "dropzone"},
|
||||
"a": {"rel", "rev"},
|
||||
"link": {"rel", "rev"},
|
||||
"td": {"headers"},
|
||||
"th": {"headers"},
|
||||
"form": {"accept-charset"},
|
||||
"object": {"archive"},
|
||||
# These are HTML5 specific, as are *.accesskey and *.dropzone above.
|
||||
"area": {"rel"},
|
||||
"icon": {"sizes"},
|
||||
"iframe": {"sandbox"},
|
||||
"output": {"for"},
|
||||
}
|
||||
|
||||
#: By default, whitespace inside these HTML tags will be
|
||||
#: preserved rather than being collapsed.
|
||||
DEFAULT_PRESERVE_WHITESPACE_TAGS: set[str] = set(["pre", "textarea"])
|
||||
|
||||
def set_up_substitutions(self, tag: Tag) -> bool:
|
||||
"""Replace the declared encoding in a <meta> tag with a placeholder,
|
||||
to be substituted when the tag is output to a string.
|
||||
|
||||
An HTML document may come in to Beautiful Soup as one
|
||||
encoding, but exit in a different encoding, and the <meta> tag
|
||||
needs to be changed to reflect this.
|
||||
|
||||
:return: Whether or not a substitution was performed.
|
||||
|
||||
:meta private:
|
||||
"""
|
||||
# We are only interested in <meta> tags
|
||||
if tag.name != "meta":
|
||||
return False
|
||||
|
||||
# TODO: This cast will fail in the (very unlikely) scenario
|
||||
# that the programmer who instantiates the TreeBuilder
|
||||
# specifies meta['content'] or meta['charset'] as
|
||||
# cdata_list_attributes.
|
||||
content: Optional[str] = cast(Optional[str], tag.get("content"))
|
||||
charset: Optional[str] = cast(Optional[str], tag.get("charset"))
|
||||
|
||||
# But we can accommodate meta['http-equiv'] being made a
|
||||
# cdata_list_attribute (again, very unlikely) without much
|
||||
# trouble.
|
||||
http_equiv: List[str] = tag.get_attribute_list("http-equiv")
|
||||
|
||||
# We are interested in <meta> tags that say what encoding the
|
||||
# document was originally in. This means HTML 5-style <meta>
|
||||
# tags that provide the "charset" attribute. It also means
|
||||
# HTML 4-style <meta> tags that provide the "content"
|
||||
# attribute and have "http-equiv" set to "content-type".
|
||||
#
|
||||
# In both cases we will replace the value of the appropriate
|
||||
# attribute with a standin object that can take on any
|
||||
# encoding.
|
||||
substituted = False
|
||||
if charset is not None:
|
||||
# HTML 5 style:
|
||||
# <meta charset="utf8">
|
||||
tag["charset"] = CharsetMetaAttributeValue(charset)
|
||||
substituted = True
|
||||
|
||||
elif content is not None and any(
|
||||
x.lower() == "content-type" for x in http_equiv
|
||||
):
|
||||
# HTML 4 style:
|
||||
# <meta http-equiv="content-type" content="text/html; charset=utf8">
|
||||
tag["content"] = ContentMetaAttributeValue(content)
|
||||
substituted = True
|
||||
|
||||
return substituted
|
||||
|
||||
|
||||
class DetectsXMLParsedAsHTML(object):
|
||||
"""A mixin class for any class (a TreeBuilder, or some class used by a
|
||||
TreeBuilder) that's in a position to detect whether an XML
|
||||
document is being incorrectly parsed as HTML, and issue an
|
||||
appropriate warning.
|
||||
|
||||
This requires being able to observe an incoming processing
|
||||
instruction that might be an XML declaration, and also able to
|
||||
observe tags as they're opened. If you can't do that for a given
|
||||
`TreeBuilder`, there's a less reliable implementation based on
|
||||
examining the raw markup.
|
||||
"""
|
||||
|
||||
#: Regular expression for seeing if string markup has an <html> tag.
|
||||
LOOKS_LIKE_HTML: Pattern[str] = re.compile("<[^ +]html", re.I)
|
||||
|
||||
#: Regular expression for seeing if byte markup has an <html> tag.
|
||||
LOOKS_LIKE_HTML_B: Pattern[bytes] = re.compile(b"<[^ +]html", re.I)
|
||||
|
||||
#: The start of an XML document string.
|
||||
XML_PREFIX: str = "<?xml"
|
||||
|
||||
#: The start of an XML document bytestring.
|
||||
XML_PREFIX_B: bytes = b"<?xml"
|
||||
|
||||
# This is typed as str, not `ProcessingInstruction`, because this
|
||||
# check may be run before any Beautiful Soup objects are created.
|
||||
_first_processing_instruction: Optional[str] #: :meta private:
|
||||
_root_tag_name: Optional[str] #: :meta private:
|
||||
|
||||
@classmethod
|
||||
def warn_if_markup_looks_like_xml(
|
||||
cls, markup: Optional[_RawMarkup], stacklevel: int = 3
|
||||
) -> bool:
|
||||
"""Perform a check on some markup to see if it looks like XML
|
||||
that's not XHTML. If so, issue a warning.
|
||||
|
||||
This is much less reliable than doing the check while parsing,
|
||||
but some of the tree builders can't do that.
|
||||
|
||||
:param stacklevel: The stacklevel of the code calling this\
|
||||
function.
|
||||
|
||||
:return: True if the markup looks like non-XHTML XML, False
|
||||
otherwise.
|
||||
"""
|
||||
if markup is None:
|
||||
return False
|
||||
markup = markup[:500]
|
||||
if isinstance(markup, bytes):
|
||||
markup_b: bytes = markup
|
||||
looks_like_xml = markup_b.startswith(
|
||||
cls.XML_PREFIX_B
|
||||
) and not cls.LOOKS_LIKE_HTML_B.search(markup)
|
||||
else:
|
||||
markup_s: str = markup
|
||||
looks_like_xml = markup_s.startswith(
|
||||
cls.XML_PREFIX
|
||||
) and not cls.LOOKS_LIKE_HTML.search(markup)
|
||||
|
||||
if looks_like_xml:
|
||||
cls._warn(stacklevel=stacklevel + 2)
|
||||
return True
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def _warn(cls, stacklevel: int = 5) -> None:
|
||||
"""Issue a warning about XML being parsed as HTML."""
|
||||
warnings.warn(
|
||||
XMLParsedAsHTMLWarning.MESSAGE,
|
||||
XMLParsedAsHTMLWarning,
|
||||
stacklevel=stacklevel,
|
||||
)
|
||||
|
||||
def _initialize_xml_detector(self) -> None:
|
||||
"""Call this method before parsing a document."""
|
||||
self._first_processing_instruction = None
|
||||
self._root_tag_name = None
|
||||
|
||||
def _document_might_be_xml(self, processing_instruction: str) -> None:
|
||||
"""Call this method when encountering an XML declaration, or a
|
||||
"processing instruction" that might be an XML declaration.
|
||||
|
||||
This helps Beautiful Soup detect potential issues later, if
|
||||
the XML document turns out to be a non-XHTML document that's
|
||||
being parsed as XML.
|
||||
"""
|
||||
if (
|
||||
self._first_processing_instruction is not None
|
||||
or self._root_tag_name is not None
|
||||
):
|
||||
# The document has already started. Don't bother checking
|
||||
# anymore.
|
||||
return
|
||||
|
||||
self._first_processing_instruction = processing_instruction
|
||||
|
||||
# We won't know until we encounter the first tag whether or
|
||||
# not this is actually a problem.
|
||||
|
||||
def _root_tag_encountered(self, name: str) -> None:
|
||||
"""Call this when you encounter the document's root tag.
|
||||
|
||||
This is where we actually check whether an XML document is
|
||||
being incorrectly parsed as HTML, and issue the warning.
|
||||
"""
|
||||
if self._root_tag_name is not None:
|
||||
# This method was incorrectly called multiple times. Do
|
||||
# nothing.
|
||||
return
|
||||
|
||||
self._root_tag_name = name
|
||||
|
||||
if (
|
||||
name != "html"
|
||||
and self._first_processing_instruction is not None
|
||||
and self._first_processing_instruction.lower().startswith("xml ")
|
||||
):
|
||||
# We encountered an XML declaration and then a tag other
|
||||
# than 'html'. This is a reliable indicator that a
|
||||
# non-XHTML document is being parsed as XML.
|
||||
self._warn(stacklevel=10)
|
||||
|
||||
|
||||
def register_treebuilders_from(module: ModuleType) -> None:
|
||||
"""Copy TreeBuilders from the given module into this module."""
|
||||
this_module = sys.modules[__name__]
|
||||
for name in module.__all__:
|
||||
obj = getattr(module, name)
|
||||
|
||||
if issubclass(obj, TreeBuilder):
|
||||
setattr(this_module, name, obj)
|
||||
this_module.__all__.append(name)
|
||||
# Register the builder while we're at it.
|
||||
this_module.builder_registry.register(obj)
|
||||
|
||||
|
||||
# Builders are registered in reverse order of priority, so that custom
|
||||
# builder registrations will take precedence. In general, we want lxml
|
||||
# to take precedence over html5lib, because it's faster. And we only
|
||||
# want to use HTMLParser as a last resort.
|
||||
from . import _htmlparser # noqa: E402
|
||||
|
||||
register_treebuilders_from(_htmlparser)
|
||||
try:
|
||||
from . import _html5lib
|
||||
|
||||
register_treebuilders_from(_html5lib)
|
||||
except ImportError:
|
||||
# They don't have html5lib installed.
|
||||
pass
|
||||
try:
|
||||
from . import _lxml
|
||||
|
||||
register_treebuilders_from(_lxml)
|
||||
except ImportError:
|
||||
# They don't have lxml installed.
|
||||
pass
|
||||
+611
@@ -0,0 +1,611 @@
|
||||
# Use of this source code is governed by the MIT license.
|
||||
__license__ = "MIT"
|
||||
|
||||
__all__ = [
|
||||
"HTML5TreeBuilder",
|
||||
]
|
||||
|
||||
from typing import (
|
||||
Any,
|
||||
cast,
|
||||
Dict,
|
||||
Iterable,
|
||||
Optional,
|
||||
Sequence,
|
||||
TYPE_CHECKING,
|
||||
Tuple,
|
||||
Union,
|
||||
)
|
||||
from typing_extensions import TypeAlias
|
||||
from bs4._typing import (
|
||||
_AttributeValue,
|
||||
_AttributeValues,
|
||||
_Encoding,
|
||||
_Encodings,
|
||||
_NamespaceURL,
|
||||
_RawMarkup,
|
||||
)
|
||||
|
||||
import warnings
|
||||
from bs4.builder import (
|
||||
DetectsXMLParsedAsHTML,
|
||||
PERMISSIVE,
|
||||
HTML,
|
||||
HTML_5,
|
||||
HTMLTreeBuilder,
|
||||
)
|
||||
from bs4.element import (
|
||||
NamespacedAttribute,
|
||||
PageElement,
|
||||
nonwhitespace_re,
|
||||
)
|
||||
import html5lib
|
||||
from html5lib.constants import (
|
||||
namespaces,
|
||||
)
|
||||
from bs4.element import (
|
||||
Comment,
|
||||
Doctype,
|
||||
NavigableString,
|
||||
Tag,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
from html5lib.treebuilders import base as treebuilder_base
|
||||
|
||||
|
||||
class HTML5TreeBuilder(HTMLTreeBuilder):
|
||||
"""Use `html5lib <https://github.com/html5lib/html5lib-python>`_ to
|
||||
build a tree.
|
||||
|
||||
Note that `HTML5TreeBuilder` does not support some common HTML
|
||||
`TreeBuilder` features. Some of these features could theoretically
|
||||
be implemented, but at the very least it's quite difficult,
|
||||
because html5lib moves the parse tree around as it's being built.
|
||||
|
||||
Specifically:
|
||||
|
||||
* This `TreeBuilder` doesn't use different subclasses of
|
||||
`NavigableString` (e.g. `Script`) based on the name of the tag
|
||||
in which the string was found.
|
||||
* You can't use a `SoupStrainer` to parse only part of a document.
|
||||
"""
|
||||
|
||||
NAME: str = "html5lib"
|
||||
|
||||
features: Iterable[str] = [NAME, PERMISSIVE, HTML_5, HTML]
|
||||
|
||||
#: html5lib can tell us which line number and position in the
|
||||
#: original file is the source of an element.
|
||||
TRACKS_LINE_NUMBERS: bool = True
|
||||
|
||||
underlying_builder: "TreeBuilderForHtml5lib" #: :meta private:
|
||||
user_specified_encoding: Optional[_Encoding]
|
||||
|
||||
def prepare_markup(
|
||||
self,
|
||||
markup: _RawMarkup,
|
||||
user_specified_encoding: Optional[_Encoding] = None,
|
||||
document_declared_encoding: Optional[_Encoding] = None,
|
||||
exclude_encodings: Optional[_Encodings] = None,
|
||||
) -> Iterable[Tuple[_RawMarkup, Optional[_Encoding], Optional[_Encoding], bool]]:
|
||||
# Store the user-specified encoding for use later on.
|
||||
self.user_specified_encoding = user_specified_encoding
|
||||
|
||||
# document_declared_encoding and exclude_encodings aren't used
|
||||
# ATM because the html5lib TreeBuilder doesn't use
|
||||
# UnicodeDammit.
|
||||
for variable, name in (
|
||||
(document_declared_encoding, "document_declared_encoding"),
|
||||
(exclude_encodings, "exclude_encodings"),
|
||||
):
|
||||
if variable:
|
||||
warnings.warn(
|
||||
f"You provided a value for {name}, but the html5lib tree builder doesn't support {name}.",
|
||||
stacklevel=3,
|
||||
)
|
||||
|
||||
# html5lib only parses HTML, so if it's given XML that's worth
|
||||
# noting.
|
||||
DetectsXMLParsedAsHTML.warn_if_markup_looks_like_xml(markup, stacklevel=3)
|
||||
|
||||
yield (markup, None, None, False)
|
||||
|
||||
# These methods are defined by Beautiful Soup.
|
||||
def feed(self, markup: _RawMarkup) -> None:
|
||||
"""Run some incoming markup through some parsing process,
|
||||
populating the `BeautifulSoup` object in `HTML5TreeBuilder.soup`.
|
||||
"""
|
||||
if self.soup is not None and self.soup.parse_only is not None:
|
||||
warnings.warn(
|
||||
"You provided a value for parse_only, but the html5lib tree builder doesn't support parse_only. The entire document will be parsed.",
|
||||
stacklevel=4,
|
||||
)
|
||||
|
||||
# self.underlying_builder is probably None now, but it'll be set
|
||||
# when html5lib calls self.create_treebuilder().
|
||||
parser = html5lib.HTMLParser(tree=self.create_treebuilder)
|
||||
assert self.underlying_builder is not None
|
||||
self.underlying_builder.parser = parser
|
||||
extra_kwargs = dict()
|
||||
if not isinstance(markup, str):
|
||||
# kwargs, specifically override_encoding, will eventually
|
||||
# be passed in to html5lib's
|
||||
# HTMLBinaryInputStream.__init__.
|
||||
extra_kwargs["override_encoding"] = self.user_specified_encoding
|
||||
|
||||
doc = parser.parse(markup, **extra_kwargs) # type:ignore
|
||||
|
||||
# Set the character encoding detected by the tokenizer.
|
||||
if isinstance(markup, str):
|
||||
# We need to special-case this because html5lib sets
|
||||
# charEncoding to UTF-8 if it gets Unicode input.
|
||||
doc.original_encoding = None
|
||||
else:
|
||||
original_encoding = parser.tokenizer.stream.charEncoding[0] # type:ignore
|
||||
# The encoding is an html5lib Encoding object. We want to
|
||||
# use a string for compatibility with other tree builders.
|
||||
original_encoding = original_encoding.name
|
||||
doc.original_encoding = original_encoding
|
||||
self.underlying_builder.parser = None
|
||||
|
||||
def create_treebuilder(
|
||||
self, namespaceHTMLElements: bool
|
||||
) -> "TreeBuilderForHtml5lib":
|
||||
"""Called by html5lib to instantiate the kind of class it
|
||||
calls a 'TreeBuilder'.
|
||||
|
||||
:param namespaceHTMLElements: Whether or not to namespace HTML elements.
|
||||
|
||||
:meta private:
|
||||
"""
|
||||
self.underlying_builder = TreeBuilderForHtml5lib(
|
||||
namespaceHTMLElements, self.soup, store_line_numbers=self.store_line_numbers
|
||||
)
|
||||
return self.underlying_builder
|
||||
|
||||
def test_fragment_to_document(self, fragment: str) -> str:
|
||||
"""See `TreeBuilder`."""
|
||||
return "<html><head></head><body>%s</body></html>" % fragment
|
||||
|
||||
|
||||
class TreeBuilderForHtml5lib(treebuilder_base.TreeBuilder):
|
||||
soup: "BeautifulSoup" #: :meta private:
|
||||
parser: Optional[html5lib.HTMLParser] #: :meta private:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
namespaceHTMLElements: bool,
|
||||
soup: Optional["BeautifulSoup"] = None,
|
||||
store_line_numbers: bool = True,
|
||||
**kwargs: Any,
|
||||
):
|
||||
if soup:
|
||||
self.soup = soup
|
||||
else:
|
||||
warnings.warn(
|
||||
"The optionality of the 'soup' argument to the TreeBuilderForHtml5lib constructor is deprecated as of Beautiful Soup 4.13.0: 'soup' is now required. If you can't pass in a BeautifulSoup object here, or you get this warning and it seems mysterious to you, please contact the Beautiful Soup developer team for possible un-deprecation.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
# TODO: Why is the parser 'html.parser' here? Using
|
||||
# html5lib doesn't cause an infinite loop and is more
|
||||
# accurate. Best to get rid of this entire section, I think.
|
||||
self.soup = BeautifulSoup(
|
||||
"", "html.parser", store_line_numbers=store_line_numbers, **kwargs
|
||||
)
|
||||
# TODO: What are **kwargs exactly? Should they be passed in
|
||||
# here in addition to/instead of being passed to the BeautifulSoup
|
||||
# constructor?
|
||||
super(TreeBuilderForHtml5lib, self).__init__(namespaceHTMLElements)
|
||||
|
||||
# This will be set later to a real html5lib HTMLParser object,
|
||||
# which we can use to track the current line number.
|
||||
self.parser = None
|
||||
self.store_line_numbers = store_line_numbers
|
||||
|
||||
def documentClass(self) -> "Element":
|
||||
self.soup.reset()
|
||||
return Element(self.soup, self.soup, None)
|
||||
|
||||
def insertDoctype(self, token: Dict[str, Any]) -> None:
|
||||
name: str = cast(str, token["name"])
|
||||
publicId: Optional[str] = cast(Optional[str], token["publicId"])
|
||||
systemId: Optional[str] = cast(Optional[str], token["systemId"])
|
||||
|
||||
doctype = Doctype.for_name_and_ids(name, publicId, systemId)
|
||||
self.soup.object_was_parsed(doctype)
|
||||
|
||||
def elementClass(self, name: str, namespace: str) -> "Element":
|
||||
sourceline: Optional[int] = None
|
||||
sourcepos: Optional[int] = None
|
||||
if self.parser is not None and self.store_line_numbers:
|
||||
# This represents the point immediately after the end of the
|
||||
# tag. We don't know when the tag started, but we do know
|
||||
# where it ended -- the character just before this one.
|
||||
sourceline, sourcepos = self.parser.tokenizer.stream.position() # type:ignore
|
||||
assert sourcepos is not None
|
||||
sourcepos = sourcepos - 1
|
||||
tag = self.soup.new_tag(
|
||||
name, namespace, sourceline=sourceline, sourcepos=sourcepos
|
||||
)
|
||||
|
||||
return Element(tag, self.soup, namespace)
|
||||
|
||||
def commentClass(self, data: str) -> "TextNode":
|
||||
return TextNode(Comment(data), self.soup)
|
||||
|
||||
def fragmentClass(self) -> "Element":
|
||||
"""This is only used by html5lib HTMLParser.parseFragment(),
|
||||
which is never used by Beautiful Soup, only by the html5lib
|
||||
unit tests. Since we don't currently hook into those tests,
|
||||
the implementation is left blank.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def getFragment(self) -> "Element":
|
||||
"""This is only used by the html5lib unit tests. Since we
|
||||
don't currently hook into those tests, the implementation is
|
||||
left blank.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def appendChild(self, node: "Element") -> None:
|
||||
# TODO: This code is not covered by the BS4 tests, and
|
||||
# apparently not triggered by the html5lib test suite either.
|
||||
# But it doesn't seem test-specific and there are calls to it
|
||||
# (or a method with the same name) all over html5lib, so I'm
|
||||
# leaving the implementation in place rather than replacing it
|
||||
# with NotImplementedError()
|
||||
self.soup.append(node.element)
|
||||
|
||||
def getDocument(self) -> "BeautifulSoup":
|
||||
return self.soup
|
||||
|
||||
def testSerializer(self, node: "Element") -> None:
|
||||
"""This is only used by the html5lib unit tests. Since we
|
||||
don't currently hook into those tests, the implementation is
|
||||
left blank.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
class AttrList(object):
|
||||
"""Represents a Tag's attributes in a way compatible with html5lib."""
|
||||
|
||||
element: Tag
|
||||
attrs: _AttributeValues
|
||||
|
||||
def __init__(self, element: Tag):
|
||||
self.element = element
|
||||
self.attrs = dict(self.element.attrs)
|
||||
|
||||
def __iter__(self) -> Iterable[Tuple[str, _AttributeValue]]:
|
||||
return list(self.attrs.items()).__iter__()
|
||||
|
||||
def __setitem__(self, name: str, value: _AttributeValue) -> None:
|
||||
# If this attribute is a multi-valued attribute for this element,
|
||||
# turn its value into a list.
|
||||
list_attr = self.element.cdata_list_attributes or {}
|
||||
if name in list_attr.get("*", []) or (
|
||||
self.element.name in list_attr
|
||||
and name in list_attr.get(self.element.name, [])
|
||||
):
|
||||
# A node that is being cloned may have already undergone
|
||||
# this procedure. Check for this and skip it.
|
||||
if not isinstance(value, list):
|
||||
assert isinstance(value, str)
|
||||
value = self.element.attribute_value_list_class(
|
||||
nonwhitespace_re.findall(value)
|
||||
)
|
||||
self.element[name] = value
|
||||
|
||||
def items(self) -> Iterable[Tuple[str, _AttributeValue]]:
|
||||
return list(self.attrs.items())
|
||||
|
||||
def keys(self) -> Iterable[str]:
|
||||
return list(self.attrs.keys())
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self.attrs)
|
||||
|
||||
def __getitem__(self, name: str) -> _AttributeValue:
|
||||
return self.attrs[name]
|
||||
|
||||
def __contains__(self, name: str) -> bool:
|
||||
return name in list(self.attrs.keys())
|
||||
|
||||
|
||||
class BeautifulSoupNode(treebuilder_base.Node):
|
||||
# A node can correspond to _either_ a Tag _or_ a NavigableString.
|
||||
tag: Optional[Tag]
|
||||
string: Optional[NavigableString]
|
||||
soup: "BeautifulSoup"
|
||||
namespace: Optional[_NamespaceURL]
|
||||
|
||||
@property
|
||||
def element(self) -> PageElement:
|
||||
assert self.tag is not None or self.string is not None
|
||||
if self.tag is not None:
|
||||
return self.tag
|
||||
else:
|
||||
assert self.string is not None
|
||||
return self.string
|
||||
|
||||
@property
|
||||
def nodeType(self) -> int:
|
||||
"""Return the html5lib constant corresponding to the type of
|
||||
the underlying DOM object.
|
||||
|
||||
NOTE: This property is only accessed by the html5lib test
|
||||
suite, not by Beautiful Soup proper.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
# TODO-TYPING: typeshed stubs are incorrect about this;
|
||||
# cloneNode returns a new Node, not None.
|
||||
def cloneNode(self) -> treebuilder_base.Node: # type:ignore
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
class Element(BeautifulSoupNode):
|
||||
namespace: Optional[_NamespaceURL]
|
||||
|
||||
def __init__(
|
||||
self, element: Tag, soup: "BeautifulSoup", namespace: Optional[_NamespaceURL]
|
||||
):
|
||||
self.tag = element
|
||||
self.string = None
|
||||
self.soup = soup
|
||||
self.namespace = namespace
|
||||
treebuilder_base.Node.__init__(self, element.name)
|
||||
|
||||
def appendChild(self, node: "BeautifulSoupNode") -> None:
|
||||
string_child: Optional[NavigableString] = None
|
||||
child: PageElement
|
||||
if type(node.string) is NavigableString:
|
||||
# We check for NavigableString *only* because we want to avoid
|
||||
# joining PreformattedStrings, such as Comments, with nearby strings.
|
||||
string_child = child = node.string
|
||||
else:
|
||||
child = node.element
|
||||
node.parent = self
|
||||
|
||||
if (
|
||||
child is not None
|
||||
and child.parent is not None
|
||||
and not isinstance(child, str)
|
||||
):
|
||||
node.element.extract()
|
||||
|
||||
if (
|
||||
string_child is not None
|
||||
and self.tag is not None and self.tag.contents
|
||||
and type(self.tag.contents[-1]) is NavigableString
|
||||
):
|
||||
# We are appending a string onto another string.
|
||||
# TODO This has O(n^2) performance, for input like
|
||||
# "a</a>a</a>a</a>..."
|
||||
old_element = self.tag.contents[-1]
|
||||
new_element = self.soup.new_string(old_element + string_child)
|
||||
old_element.replace_with(new_element)
|
||||
self.soup._most_recent_element = new_element
|
||||
else:
|
||||
if isinstance(node, str):
|
||||
# Create a brand new NavigableString from this string.
|
||||
child = self.soup.new_string(node)
|
||||
|
||||
# Tell Beautiful Soup to act as if it parsed this element
|
||||
# immediately after the parent's last descendant. (Or
|
||||
# immediately after the parent, if it has no children.)
|
||||
if self.tag is not None and self.tag.contents:
|
||||
most_recent_element = self.tag._last_descendant(False)
|
||||
elif self.element.next_element is not None:
|
||||
# Something from further ahead in the parse tree is
|
||||
# being inserted into this earlier element. This is
|
||||
# very annoying because it means an expensive search
|
||||
# for the last element in the tree.
|
||||
most_recent_element = self.soup._last_descendant()
|
||||
else:
|
||||
most_recent_element = self.element
|
||||
|
||||
self.soup.object_was_parsed(
|
||||
child, parent=self.tag, most_recent_element=most_recent_element
|
||||
)
|
||||
|
||||
def getAttributes(self) -> AttrList:
|
||||
assert self.tag is not None
|
||||
return AttrList(self.tag)
|
||||
|
||||
# An HTML5lib attribute name may either be a single string,
|
||||
# or a tuple (namespace, name).
|
||||
_Html5libAttributeName: TypeAlias = Union[str, Tuple[str, str]]
|
||||
# Now we can define the type this method accepts as a dictionary
|
||||
# mapping those attribute names to single string values.
|
||||
_Html5libAttributes: TypeAlias = Dict[_Html5libAttributeName, str]
|
||||
|
||||
def setAttributes(self, attributes: Optional[_Html5libAttributes]) -> None:
|
||||
assert self.tag is not None
|
||||
if attributes is not None and len(attributes) > 0:
|
||||
# Replace any namespaced attributes with
|
||||
# NamespacedAttribute objects.
|
||||
for name, value in list(attributes.items()):
|
||||
if isinstance(name, tuple):
|
||||
new_name = NamespacedAttribute(*name)
|
||||
del attributes[name]
|
||||
attributes[new_name] = value
|
||||
|
||||
# We can now cast attributes to the type of Dict
|
||||
# used by Beautiful Soup.
|
||||
normalized_attributes = cast(_AttributeValues, attributes)
|
||||
|
||||
# Values for tags like 'class' came in as single strings;
|
||||
# replace them with lists of strings as appropriate.
|
||||
self.soup.builder._replace_cdata_list_attribute_values(
|
||||
self.name, normalized_attributes
|
||||
)
|
||||
|
||||
# Then set the attributes on the Tag associated with this
|
||||
# BeautifulSoupNode.
|
||||
for name, value_or_values in list(normalized_attributes.items()):
|
||||
self.tag[name] = value_or_values
|
||||
|
||||
# The attributes may contain variables that need substitution.
|
||||
# Call set_up_substitutions manually.
|
||||
#
|
||||
# The Tag constructor called this method when the Tag was created,
|
||||
# but we just set/changed the attributes, so call it again.
|
||||
self.soup.builder.set_up_substitutions(self.tag)
|
||||
|
||||
attributes = property(getAttributes, setAttributes)
|
||||
|
||||
def insertText(
|
||||
self, data: str, insertBefore: Optional["BeautifulSoupNode"] = None
|
||||
) -> None:
|
||||
text = TextNode(self.soup.new_string(data), self.soup)
|
||||
if insertBefore:
|
||||
self.insertBefore(text, insertBefore)
|
||||
else:
|
||||
self.appendChild(text)
|
||||
|
||||
def insertBefore(
|
||||
self, node: "BeautifulSoupNode", refNode: "BeautifulSoupNode"
|
||||
) -> None:
|
||||
assert self.tag is not None
|
||||
index = self.tag.index(refNode.element)
|
||||
if (
|
||||
type(node.element) is NavigableString
|
||||
and self.tag.contents
|
||||
and type(self.tag.contents[index - 1]) is NavigableString
|
||||
):
|
||||
# (See comments in appendChild)
|
||||
old_node = self.tag.contents[index - 1]
|
||||
assert type(old_node) is NavigableString
|
||||
new_str = self.soup.new_string(old_node + node.element)
|
||||
old_node.replace_with(new_str)
|
||||
else:
|
||||
self.tag.insert(index, node.element)
|
||||
node.parent = self
|
||||
|
||||
def removeChild(self, node: "Element") -> None:
|
||||
node.element.extract()
|
||||
|
||||
def reparentChildren(self, newParent: "Element") -> None:
|
||||
"""Move all of this tag's children into another tag."""
|
||||
# print("MOVE", self.element.contents)
|
||||
# print("FROM", self.element)
|
||||
# print("TO", new_parent.element)
|
||||
|
||||
element = self.tag
|
||||
assert element is not None
|
||||
new_parent_element = newParent.tag
|
||||
assert new_parent_element is not None
|
||||
# Determine what this tag's next_element will be once all the children
|
||||
# are removed.
|
||||
final_next_element = element.next_sibling
|
||||
|
||||
new_parents_last_descendant = new_parent_element._last_descendant(False, False)
|
||||
if len(new_parent_element.contents) > 0:
|
||||
# The new parent already contains children. We will be
|
||||
# appending this tag's children to the end.
|
||||
|
||||
# We can make this assertion since we know new_parent has
|
||||
# children.
|
||||
assert new_parents_last_descendant is not None
|
||||
new_parents_last_child = new_parent_element.contents[-1]
|
||||
new_parents_last_descendant_next_element = (
|
||||
new_parents_last_descendant.next_element
|
||||
)
|
||||
else:
|
||||
# The new parent contains no children.
|
||||
new_parents_last_child = None
|
||||
new_parents_last_descendant_next_element = new_parent_element.next_element
|
||||
|
||||
to_append = element.contents
|
||||
if len(to_append) > 0:
|
||||
# Set the first child's previous_element and previous_sibling
|
||||
# to elements within the new parent
|
||||
first_child = to_append[0]
|
||||
if new_parents_last_descendant is not None:
|
||||
first_child.previous_element = new_parents_last_descendant
|
||||
else:
|
||||
first_child.previous_element = new_parent_element
|
||||
first_child.previous_sibling = new_parents_last_child
|
||||
if new_parents_last_descendant is not None:
|
||||
new_parents_last_descendant.next_element = first_child
|
||||
else:
|
||||
new_parent_element.next_element = first_child
|
||||
if new_parents_last_child is not None:
|
||||
new_parents_last_child.next_sibling = first_child
|
||||
|
||||
# Find the very last element being moved. It is now the
|
||||
# parent's last descendant. It has no .next_sibling and
|
||||
# its .next_element is whatever the previous last
|
||||
# descendant had.
|
||||
last_childs_last_descendant = to_append[-1]._last_descendant(
|
||||
is_initialized=False, accept_self=True
|
||||
)
|
||||
|
||||
# Since we passed accept_self=True into _last_descendant,
|
||||
# there's no possibility that the result is None.
|
||||
assert last_childs_last_descendant is not None
|
||||
last_childs_last_descendant.next_element = (
|
||||
new_parents_last_descendant_next_element
|
||||
)
|
||||
if new_parents_last_descendant_next_element is not None:
|
||||
# TODO-COVERAGE: This code has no test coverage and
|
||||
# I'm not sure how to get html5lib to go through this
|
||||
# path, but it's just the other side of the previous
|
||||
# line.
|
||||
new_parents_last_descendant_next_element.previous_element = (
|
||||
last_childs_last_descendant
|
||||
)
|
||||
last_childs_last_descendant.next_sibling = None
|
||||
|
||||
for child in to_append:
|
||||
child.parent = new_parent_element
|
||||
new_parent_element.contents.append(child)
|
||||
|
||||
# Now that this element has no children, change its .next_element.
|
||||
element.contents = []
|
||||
element.next_element = final_next_element
|
||||
|
||||
# print("DONE WITH MOVE")
|
||||
# print("FROM", self.element)
|
||||
# print("TO", new_parent_element)
|
||||
|
||||
# TODO-TYPING: typeshed stubs are incorrect about this;
|
||||
# hasContent returns a boolean, not None.
|
||||
def hasContent(self) -> bool: # type:ignore
|
||||
return self.tag is None or len(self.tag.contents) > 0
|
||||
|
||||
# TODO-TYPING: typeshed stubs are incorrect about this;
|
||||
# cloneNode returns a new Node, not None.
|
||||
def cloneNode(self) -> treebuilder_base.Node: # type:ignore
|
||||
assert self.tag is not None
|
||||
tag = self.soup.new_tag(self.tag.name, self.namespace)
|
||||
node = Element(tag, self.soup, self.namespace)
|
||||
for key, value in self.attributes:
|
||||
node.attributes[key] = value
|
||||
return node
|
||||
|
||||
def getNameTuple(self) -> Tuple[Optional[_NamespaceURL], str]:
|
||||
if self.namespace is None:
|
||||
return namespaces["html"], self.name
|
||||
else:
|
||||
return self.namespace, self.name
|
||||
|
||||
nameTuple = property(getNameTuple)
|
||||
|
||||
|
||||
class TextNode(BeautifulSoupNode):
|
||||
|
||||
def __init__(self, element: NavigableString, soup: "BeautifulSoup"):
|
||||
treebuilder_base.Node.__init__(self, None)
|
||||
self.tag = None
|
||||
self.string = element
|
||||
self.soup = soup
|
||||
@@ -0,0 +1,517 @@
|
||||
# encoding: utf-8
|
||||
"""Use the HTMLParser library to parse HTML files that aren't too bad."""
|
||||
from __future__ import annotations
|
||||
|
||||
# Use of this source code is governed by the MIT license.
|
||||
__license__ = "MIT"
|
||||
|
||||
__all__ = [
|
||||
"HTMLParserTreeBuilder",
|
||||
]
|
||||
|
||||
from html.parser import HTMLParser
|
||||
import re
|
||||
|
||||
from typing import (
|
||||
Any,
|
||||
Callable,
|
||||
cast,
|
||||
Dict,
|
||||
Iterable,
|
||||
List,
|
||||
Optional,
|
||||
TYPE_CHECKING,
|
||||
Tuple,
|
||||
Type,
|
||||
Union,
|
||||
)
|
||||
|
||||
from bs4.element import (
|
||||
AttributeDict,
|
||||
CData,
|
||||
Comment,
|
||||
Declaration,
|
||||
Doctype,
|
||||
ProcessingInstruction,
|
||||
)
|
||||
from bs4.dammit import EntitySubstitution, UnicodeDammit
|
||||
|
||||
from bs4.builder import (
|
||||
DetectsXMLParsedAsHTML,
|
||||
HTML,
|
||||
HTMLTreeBuilder,
|
||||
STRICT,
|
||||
)
|
||||
|
||||
from bs4.exceptions import ParserRejectedMarkup
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from bs4 import BeautifulSoup
|
||||
from bs4.element import NavigableString
|
||||
from bs4._typing import (
|
||||
_Encoding,
|
||||
_Encodings,
|
||||
_RawMarkup,
|
||||
)
|
||||
|
||||
HTMLPARSER = "html.parser"
|
||||
|
||||
_DuplicateAttributeHandler = Callable[[Dict[str, str], str, str], None]
|
||||
|
||||
|
||||
class BeautifulSoupHTMLParser(HTMLParser, DetectsXMLParsedAsHTML):
|
||||
#: Constant to handle duplicate attributes by ignoring later values
|
||||
#: and keeping the earlier ones.
|
||||
REPLACE: str = "replace"
|
||||
|
||||
#: Constant to handle duplicate attributes by replacing earlier values
|
||||
#: with later ones.
|
||||
IGNORE: str = "ignore"
|
||||
|
||||
"""A subclass of the Python standard library's HTMLParser class, which
|
||||
listens for HTMLParser events and translates them into calls
|
||||
to Beautiful Soup's tree construction API.
|
||||
|
||||
:param on_duplicate_attribute: A strategy for what to do if a
|
||||
tag includes the same attribute more than once. Accepted
|
||||
values are: REPLACE (replace earlier values with later
|
||||
ones, the default), IGNORE (keep the earliest value
|
||||
encountered), or a callable. A callable must take three
|
||||
arguments: the dictionary of attributes already processed,
|
||||
the name of the duplicate attribute, and the most recent value
|
||||
encountered.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
soup: BeautifulSoup,
|
||||
*args: Any,
|
||||
on_duplicate_attribute: Union[str, _DuplicateAttributeHandler] = REPLACE,
|
||||
**kwargs: Any,
|
||||
):
|
||||
self.soup = soup
|
||||
self.on_duplicate_attribute = on_duplicate_attribute
|
||||
self.attribute_dict_class = soup.builder.attribute_dict_class
|
||||
HTMLParser.__init__(self, *args, **kwargs)
|
||||
|
||||
# Keep a list of empty-element tags that were encountered
|
||||
# without an explicit closing tag. If we encounter a closing tag
|
||||
# of this type, we'll associate it with one of those entries.
|
||||
#
|
||||
# This isn't a stack because we don't care about the
|
||||
# order. It's a list of closing tags we've already handled and
|
||||
# will ignore, assuming they ever show up.
|
||||
self.already_closed_empty_element = []
|
||||
|
||||
self._initialize_xml_detector()
|
||||
|
||||
on_duplicate_attribute: Union[str, _DuplicateAttributeHandler]
|
||||
already_closed_empty_element: List[str]
|
||||
soup: BeautifulSoup
|
||||
|
||||
def error(self, message: str) -> None:
|
||||
# NOTE: This method is required so long as Python 3.9 is
|
||||
# supported. The corresponding code is removed from HTMLParser
|
||||
# in 3.5, but not removed from ParserBase until 3.10.
|
||||
# https://github.com/python/cpython/issues/76025
|
||||
#
|
||||
# The original implementation turned the error into a warning,
|
||||
# but in every case I discovered, this made HTMLParser
|
||||
# immediately crash with an error message that was less
|
||||
# helpful than the warning. The new implementation makes it
|
||||
# more clear that html.parser just can't parse this
|
||||
# markup. The 3.10 implementation does the same, though it
|
||||
# raises AssertionError rather than calling a method. (We
|
||||
# catch this error and wrap it in a ParserRejectedMarkup.)
|
||||
raise ParserRejectedMarkup(message)
|
||||
|
||||
def handle_startendtag(
|
||||
self, tag: str, attrs: List[Tuple[str, Optional[str]]]
|
||||
) -> None:
|
||||
"""Handle an incoming empty-element tag.
|
||||
|
||||
html.parser only calls this method when the markup looks like
|
||||
<tag/>.
|
||||
"""
|
||||
# `handle_empty_element` tells handle_starttag not to close the tag
|
||||
# just because its name matches a known empty-element tag. We
|
||||
# know that this is an empty-element tag, and we want to call
|
||||
# handle_endtag ourselves.
|
||||
self.handle_starttag(tag, attrs, handle_empty_element=False)
|
||||
|
||||
# Similarly, we set `check_already_closed` when calling
|
||||
# handle_endtag. Since we know the start event is identical to
|
||||
# the end event, we don't want handle_endtag() to cross off
|
||||
# any previous end events for tags of this name.
|
||||
self.handle_endtag(tag, check_already_closed=False)
|
||||
|
||||
def handle_starttag(
|
||||
self,
|
||||
tag: str,
|
||||
attrs: List[Tuple[str, Optional[str]]],
|
||||
handle_empty_element: bool = True,
|
||||
) -> None:
|
||||
"""Handle an opening tag, e.g. '<tag>'
|
||||
|
||||
:param handle_empty_element: True if this tag is known to be
|
||||
an empty-element tag (i.e. there is not expected to be any
|
||||
closing tag).
|
||||
"""
|
||||
# TODO: handle namespaces here?
|
||||
attr_dict: AttributeDict = self.attribute_dict_class()
|
||||
for key, value in attrs:
|
||||
# Change None attribute values to the empty string
|
||||
# for consistency with the other tree builders.
|
||||
if value is None:
|
||||
value = ""
|
||||
if key in attr_dict:
|
||||
# A single attribute shows up multiple times in this
|
||||
# tag. How to handle it depends on the
|
||||
# on_duplicate_attribute setting.
|
||||
on_dupe = self.on_duplicate_attribute
|
||||
if on_dupe == self.IGNORE:
|
||||
pass
|
||||
elif on_dupe in (None, self.REPLACE):
|
||||
attr_dict[key] = value
|
||||
else:
|
||||
on_dupe = cast(_DuplicateAttributeHandler, on_dupe)
|
||||
on_dupe(attr_dict, key, value)
|
||||
else:
|
||||
attr_dict[key] = value
|
||||
# print("START", tag)
|
||||
sourceline: Optional[int]
|
||||
sourcepos: Optional[int]
|
||||
if self.soup.builder.store_line_numbers:
|
||||
sourceline, sourcepos = self.getpos()
|
||||
else:
|
||||
sourceline = sourcepos = None
|
||||
tagObj = self.soup.handle_starttag(
|
||||
tag, None, None, attr_dict, sourceline=sourceline, sourcepos=sourcepos
|
||||
)
|
||||
if tagObj is not None and tagObj.is_empty_element and handle_empty_element:
|
||||
# Unlike other parsers, html.parser doesn't send separate end tag
|
||||
# events for empty-element tags. (It's handled in
|
||||
# handle_startendtag, but only if the original markup looked like
|
||||
# <tag/>.)
|
||||
#
|
||||
# So we need to call handle_endtag() ourselves. Since we
|
||||
# know the start event is identical to the end event, we
|
||||
# don't want handle_endtag() to cross off any previous end
|
||||
# events for tags of this name.
|
||||
self.handle_endtag(tag, check_already_closed=False)
|
||||
|
||||
# But we might encounter an explicit closing tag for this tag
|
||||
# later on. If so, we want to ignore it.
|
||||
self.already_closed_empty_element.append(tag)
|
||||
|
||||
if self._root_tag_name is None:
|
||||
self._root_tag_encountered(tag)
|
||||
|
||||
def handle_endtag(self, tag: str, check_already_closed: bool = True) -> None:
|
||||
"""Handle a closing tag, e.g. '</tag>'
|
||||
|
||||
:param tag: A tag name.
|
||||
:param check_already_closed: True if this tag is expected to
|
||||
be the closing portion of an empty-element tag,
|
||||
e.g. '<tag></tag>'.
|
||||
"""
|
||||
# print("END", tag)
|
||||
if check_already_closed and tag in self.already_closed_empty_element:
|
||||
# This is a redundant end tag for an empty-element tag.
|
||||
# We've already called handle_endtag() for it, so just
|
||||
# check it off the list.
|
||||
# print("ALREADY CLOSED", tag)
|
||||
self.already_closed_empty_element.remove(tag)
|
||||
else:
|
||||
self.soup.handle_endtag(tag)
|
||||
|
||||
def handle_data(self, data: str) -> None:
|
||||
"""Handle some textual data that shows up between tags."""
|
||||
self.soup.handle_data(data)
|
||||
|
||||
_DECIMAL_REFERENCE_WITH_FOLLOWING_DATA = re.compile("^([0-9]+)(.*)")
|
||||
_HEX_REFERENCE_WITH_FOLLOWING_DATA = re.compile("^([0-9a-f]+)(.*)")
|
||||
|
||||
@classmethod
|
||||
def _dereference_numeric_character_reference(cls, name:str) -> Tuple[str, bool, str]:
|
||||
"""Convert a numeric character reference into an actual character.
|
||||
|
||||
:param name: The number of the character reference, as
|
||||
obtained by html.parser
|
||||
|
||||
:return: A 3-tuple (dereferenced, replacement_added,
|
||||
extra_data). `dereferenced` is the dereferenced character
|
||||
reference, or the empty string if there was no
|
||||
reference. `replacement_added` is True if the reference
|
||||
could only be dereferenced by replacing content with U+FFFD
|
||||
REPLACEMENT CHARACTER. `extra_data` is a portion of data
|
||||
following the character reference, which was deemed to be
|
||||
normal data and not part of the reference at all.
|
||||
"""
|
||||
dereferenced:str = ""
|
||||
replacement_added:bool = False
|
||||
extra_data:str = ""
|
||||
|
||||
base:int = 10
|
||||
reg = cls._DECIMAL_REFERENCE_WITH_FOLLOWING_DATA
|
||||
if name.startswith("x") or name.startswith("X"):
|
||||
# Hex reference
|
||||
name = name[1:]
|
||||
base = 16
|
||||
reg = cls._HEX_REFERENCE_WITH_FOLLOWING_DATA
|
||||
|
||||
real_name:Optional[int] = None
|
||||
try:
|
||||
real_name = int(name, base)
|
||||
except ValueError:
|
||||
# This is either bad data that starts with what looks like
|
||||
# a numeric character reference, or a real numeric
|
||||
# reference that wasn't terminated by a semicolon.
|
||||
#
|
||||
# The fix to https://bugs.python.org/issue13633 made it
|
||||
# our responsibility to handle the extra data.
|
||||
#
|
||||
# To preserve the old behavior, we extract the numeric
|
||||
# portion of the incoming "reference" and treat that as a
|
||||
# numeric reference. All subsequent data will be processed
|
||||
# as string data.
|
||||
match = reg.search(name)
|
||||
if match is not None:
|
||||
real_name = int(match.groups()[0], base)
|
||||
extra_data = match.groups()[1]
|
||||
|
||||
if real_name is None:
|
||||
dereferenced = ""
|
||||
extra_data = name
|
||||
else:
|
||||
dereferenced, replacement_added = UnicodeDammit.numeric_character_reference(real_name)
|
||||
return dereferenced, replacement_added, extra_data
|
||||
|
||||
def handle_charref(self, name: str) -> None:
|
||||
"""Handle a numeric character reference by converting it to the
|
||||
corresponding Unicode character and treating it as textual
|
||||
data.
|
||||
|
||||
:param name: Character number, possibly in hexadecimal.
|
||||
"""
|
||||
dereferenced, replacement_added, extra_data = self._dereference_numeric_character_reference(name)
|
||||
if replacement_added:
|
||||
self.soup.contains_replacement_characters = True
|
||||
if dereferenced is not None:
|
||||
self.handle_data(dereferenced)
|
||||
if extra_data is not None:
|
||||
self.handle_data(extra_data)
|
||||
|
||||
def handle_entityref(self, name: str) -> None:
|
||||
"""Handle a named entity reference by converting it to the
|
||||
corresponding Unicode character(s) and treating it as textual
|
||||
data.
|
||||
|
||||
:param name: Name of the entity reference.
|
||||
"""
|
||||
character = EntitySubstitution.HTML_ENTITY_TO_CHARACTER.get(name)
|
||||
if character is not None:
|
||||
data = character
|
||||
else:
|
||||
# If this were XML, it would be ambiguous whether "&foo"
|
||||
# was an character entity reference with a missing
|
||||
# semicolon or the literal string "&foo". Since this is
|
||||
# HTML, we have a complete list of all character entity references,
|
||||
# and this one wasn't found, so assume it's the literal string "&foo".
|
||||
data = "&%s" % name
|
||||
self.handle_data(data)
|
||||
|
||||
def handle_comment(self, data: str) -> None:
|
||||
"""Handle an HTML comment.
|
||||
|
||||
:param data: The text of the comment.
|
||||
"""
|
||||
self.soup.endData()
|
||||
self.soup.handle_data(data)
|
||||
self.soup.endData(Comment)
|
||||
|
||||
def handle_decl(self, decl: str) -> None:
|
||||
"""Handle a DOCTYPE declaration.
|
||||
|
||||
:param data: The text of the declaration.
|
||||
"""
|
||||
self.soup.endData()
|
||||
decl = decl[len("DOCTYPE ") :]
|
||||
self.soup.handle_data(decl)
|
||||
self.soup.endData(Doctype)
|
||||
|
||||
def unknown_decl(self, data: str) -> None:
|
||||
"""Handle a declaration of unknown type -- probably a CDATA block.
|
||||
|
||||
:param data: The text of the declaration.
|
||||
"""
|
||||
cls: Type[NavigableString]
|
||||
if data.upper().startswith("CDATA["):
|
||||
cls = CData
|
||||
data = data[len("CDATA[") :]
|
||||
else:
|
||||
cls = Declaration
|
||||
self.soup.endData()
|
||||
self.soup.handle_data(data)
|
||||
self.soup.endData(cls)
|
||||
|
||||
def handle_pi(self, data: str) -> None:
|
||||
"""Handle a processing instruction.
|
||||
|
||||
:param data: The text of the instruction.
|
||||
"""
|
||||
self.soup.endData()
|
||||
self.soup.handle_data(data)
|
||||
self._document_might_be_xml(data)
|
||||
self.soup.endData(ProcessingInstruction)
|
||||
|
||||
|
||||
class HTMLParserTreeBuilder(HTMLTreeBuilder):
|
||||
"""A Beautiful soup `bs4.builder.TreeBuilder` that uses the
|
||||
:py:class:`html.parser.HTMLParser` parser, found in the Python
|
||||
standard library.
|
||||
|
||||
"""
|
||||
|
||||
is_xml: bool = False
|
||||
picklable: bool = True
|
||||
NAME: str = HTMLPARSER
|
||||
features: Iterable[str] = [NAME, HTML, STRICT]
|
||||
parser_args: Tuple[Iterable[Any], Dict[str, Any]]
|
||||
|
||||
#: The html.parser knows which line number and position in the
|
||||
#: original file is the source of an element.
|
||||
TRACKS_LINE_NUMBERS: bool = True
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parser_args: Optional[Iterable[Any]] = None,
|
||||
parser_kwargs: Optional[Dict[str, Any]] = None,
|
||||
**kwargs: Any,
|
||||
):
|
||||
"""Constructor.
|
||||
|
||||
:param parser_args: Positional arguments to pass into
|
||||
the BeautifulSoupHTMLParser constructor, once it's
|
||||
invoked.
|
||||
:param parser_kwargs: Keyword arguments to pass into
|
||||
the BeautifulSoupHTMLParser constructor, once it's
|
||||
invoked.
|
||||
:param kwargs: Keyword arguments for the superclass constructor.
|
||||
"""
|
||||
# Some keyword arguments will be pulled out of kwargs and placed
|
||||
# into parser_kwargs.
|
||||
extra_parser_kwargs = dict()
|
||||
for arg in ("on_duplicate_attribute",):
|
||||
if arg in kwargs:
|
||||
value = kwargs.pop(arg)
|
||||
extra_parser_kwargs[arg] = value
|
||||
super(HTMLParserTreeBuilder, self).__init__(**kwargs)
|
||||
parser_args = parser_args or []
|
||||
parser_kwargs = parser_kwargs or {}
|
||||
parser_kwargs.update(extra_parser_kwargs)
|
||||
parser_kwargs["convert_charrefs"] = False
|
||||
self.parser_args = (parser_args, parser_kwargs)
|
||||
|
||||
def prepare_markup(
|
||||
self,
|
||||
markup: _RawMarkup,
|
||||
user_specified_encoding: Optional[_Encoding] = None,
|
||||
document_declared_encoding: Optional[_Encoding] = None,
|
||||
exclude_encodings: Optional[_Encodings] = None,
|
||||
) -> Iterable[Tuple[str, Optional[_Encoding], Optional[_Encoding], bool]]:
|
||||
"""Run any preliminary steps necessary to make incoming markup
|
||||
acceptable to the parser.
|
||||
|
||||
:param markup: Some markup -- probably a bytestring.
|
||||
:param user_specified_encoding: The user asked to try this encoding.
|
||||
:param document_declared_encoding: The markup itself claims to be
|
||||
in this encoding.
|
||||
:param exclude_encodings: The user asked _not_ to try any of
|
||||
these encodings.
|
||||
|
||||
:yield: A series of 4-tuples: (markup, encoding, declared encoding,
|
||||
has undergone character replacement)
|
||||
|
||||
Each 4-tuple represents a strategy for parsing the document.
|
||||
This TreeBuilder uses Unicode, Dammit to convert the markup
|
||||
into Unicode, so the ``markup`` element of the tuple will
|
||||
always be a string.
|
||||
"""
|
||||
if isinstance(markup, str):
|
||||
# Parse Unicode as-is.
|
||||
yield (markup, None, None, False)
|
||||
return
|
||||
|
||||
# Ask UnicodeDammit to sniff the most likely encoding.
|
||||
|
||||
known_definite_encodings: List[_Encoding] = []
|
||||
if user_specified_encoding:
|
||||
# This was provided by the end-user; treat it as a known
|
||||
# definite encoding per the algorithm laid out in the
|
||||
# HTML5 spec. (See the EncodingDetector class for
|
||||
# details.)
|
||||
known_definite_encodings.append(user_specified_encoding)
|
||||
|
||||
user_encodings: List[_Encoding] = []
|
||||
if document_declared_encoding:
|
||||
# This was found in the document; treat it as a slightly
|
||||
# lower-priority user encoding.
|
||||
user_encodings.append(document_declared_encoding)
|
||||
|
||||
dammit = UnicodeDammit(
|
||||
markup,
|
||||
known_definite_encodings=known_definite_encodings,
|
||||
user_encodings=user_encodings,
|
||||
is_html=True,
|
||||
exclude_encodings=exclude_encodings,
|
||||
)
|
||||
|
||||
if dammit.unicode_markup is None:
|
||||
# In every case I've seen, Unicode, Dammit is able to
|
||||
# convert the markup into Unicode, even if it needs to use
|
||||
# REPLACEMENT CHARACTER. But there is a code path that
|
||||
# could result in unicode_markup being None, and
|
||||
# HTMLParser can only parse Unicode, so here we handle
|
||||
# that code path.
|
||||
raise ParserRejectedMarkup(
|
||||
"Could not convert input to Unicode, and html.parser will not accept bytestrings."
|
||||
)
|
||||
else:
|
||||
yield (
|
||||
dammit.unicode_markup,
|
||||
dammit.original_encoding,
|
||||
dammit.declared_html_encoding,
|
||||
dammit.contains_replacement_characters,
|
||||
)
|
||||
|
||||
def feed(self, markup: _RawMarkup, _parser_class:type[BeautifulSoupHTMLParser] =BeautifulSoupHTMLParser) -> None:
|
||||
"""
|
||||
:param markup: The markup to feed into the parser.
|
||||
:param _parser_class: An HTMLParser subclass to use. This is only intended for use in unit tests.
|
||||
"""
|
||||
args, kwargs = self.parser_args
|
||||
|
||||
# HTMLParser.feed will only handle str, but
|
||||
# BeautifulSoup.markup is allowed to be _RawMarkup, because
|
||||
# it's set by the yield value of
|
||||
# TreeBuilder.prepare_markup. Fortunately,
|
||||
# HTMLParserTreeBuilder.prepare_markup always yields a str
|
||||
# (UnicodeDammit.unicode_markup).
|
||||
assert isinstance(markup, str)
|
||||
|
||||
# We know BeautifulSoup calls TreeBuilder.initialize_soup
|
||||
# before calling feed(), so we can assume self.soup
|
||||
# is set.
|
||||
assert self.soup is not None
|
||||
parser = _parser_class(self.soup, *args, **kwargs)
|
||||
|
||||
try:
|
||||
parser.feed(markup)
|
||||
parser.close()
|
||||
except AssertionError as e:
|
||||
# html.parser raises AssertionError in rare cases to
|
||||
# indicate a fatal problem with the markup, especially
|
||||
# when there's an error in the doctype declaration.
|
||||
raise ParserRejectedMarkup(e)
|
||||
parser.already_closed_empty_element = []
|
||||
+501
@@ -0,0 +1,501 @@
|
||||
# encoding: utf-8
|
||||
from __future__ import annotations
|
||||
|
||||
# Use of this source code is governed by the MIT license.
|
||||
__license__ = "MIT"
|
||||
|
||||
__all__ = [
|
||||
"LXMLTreeBuilderForXML",
|
||||
"LXMLTreeBuilder",
|
||||
]
|
||||
|
||||
|
||||
from typing import (
|
||||
Any,
|
||||
Dict,
|
||||
Iterable,
|
||||
List,
|
||||
Optional,
|
||||
Set,
|
||||
Tuple,
|
||||
Type,
|
||||
TYPE_CHECKING,
|
||||
Union,
|
||||
)
|
||||
|
||||
from io import BytesIO
|
||||
from io import StringIO
|
||||
|
||||
from typing_extensions import TypeAlias
|
||||
|
||||
from lxml import etree # type:ignore
|
||||
from bs4.element import (
|
||||
AttributeDict,
|
||||
XMLAttributeDict,
|
||||
Comment,
|
||||
Doctype,
|
||||
NamespacedAttribute,
|
||||
ProcessingInstruction,
|
||||
XMLProcessingInstruction,
|
||||
)
|
||||
from bs4.builder import (
|
||||
DetectsXMLParsedAsHTML,
|
||||
FAST,
|
||||
HTML,
|
||||
HTMLTreeBuilder,
|
||||
PERMISSIVE,
|
||||
TreeBuilder,
|
||||
XML,
|
||||
)
|
||||
from bs4.dammit import EncodingDetector
|
||||
from bs4.exceptions import ParserRejectedMarkup
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from bs4._typing import (
|
||||
_Encoding,
|
||||
_Encodings,
|
||||
_NamespacePrefix,
|
||||
_NamespaceURL,
|
||||
_NamespaceMapping,
|
||||
_InvertedNamespaceMapping,
|
||||
_RawMarkup,
|
||||
)
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
LXML: str = "lxml"
|
||||
|
||||
|
||||
def _invert(d: dict[Any, Any]) -> dict[Any, Any]:
|
||||
"Invert a dictionary."
|
||||
return dict((v, k) for k, v in list(d.items()))
|
||||
|
||||
|
||||
_LXMLParser: TypeAlias = Union[etree.XMLParser, etree.HTMLParser]
|
||||
_ParserOrParserClass: TypeAlias = Union[
|
||||
_LXMLParser, Type[etree.XMLParser], Type[etree.HTMLParser]
|
||||
]
|
||||
|
||||
|
||||
class LXMLTreeBuilderForXML(TreeBuilder):
|
||||
DEFAULT_PARSER_CLASS: Type[etree.XMLParser] = etree.XMLParser
|
||||
|
||||
is_xml: bool = True
|
||||
|
||||
#: Set this to true (probably by passing huge_tree=True into the :
|
||||
#: BeautifulSoup constructor) to enable the lxml feature "disable security
|
||||
#: restrictions and support very deep trees and very long text
|
||||
#: content".
|
||||
huge_tree: bool
|
||||
|
||||
processing_instruction_class: Type[ProcessingInstruction]
|
||||
|
||||
NAME: str = "lxml-xml"
|
||||
ALTERNATE_NAMES: Iterable[str] = ["xml"]
|
||||
|
||||
# Well, it's permissive by XML parser standards.
|
||||
features: Iterable[str] = [NAME, LXML, XML, FAST, PERMISSIVE]
|
||||
|
||||
CHUNK_SIZE: int = 512
|
||||
|
||||
# This namespace mapping is specified in the XML Namespace
|
||||
# standard.
|
||||
DEFAULT_NSMAPS: _NamespaceMapping = dict(xml="http://www.w3.org/XML/1998/namespace")
|
||||
|
||||
DEFAULT_NSMAPS_INVERTED: _InvertedNamespaceMapping = _invert(DEFAULT_NSMAPS)
|
||||
|
||||
nsmaps: List[Optional[_InvertedNamespaceMapping]]
|
||||
empty_element_tags: Optional[Set[str]]
|
||||
parser: Any
|
||||
_default_parser: Optional[etree.XMLParser]
|
||||
|
||||
# NOTE: If we parsed Element objects and looked at .sourceline,
|
||||
# we'd be able to see the line numbers from the original document.
|
||||
# But instead we build an XMLParser or HTMLParser object to serve
|
||||
# as the target of parse messages, and those messages don't include
|
||||
# line numbers.
|
||||
# See: https://bugs.launchpad.net/lxml/+bug/1846906
|
||||
|
||||
def initialize_soup(self, soup: BeautifulSoup) -> None:
|
||||
"""Let the BeautifulSoup object know about the standard namespace
|
||||
mapping.
|
||||
|
||||
:param soup: A `BeautifulSoup`.
|
||||
"""
|
||||
# Beyond this point, self.soup is set, so we can assume (and
|
||||
# assert) it's not None whenever necessary.
|
||||
super(LXMLTreeBuilderForXML, self).initialize_soup(soup)
|
||||
self._register_namespaces(self.DEFAULT_NSMAPS)
|
||||
|
||||
def _register_namespaces(self, mapping: Dict[str, str]) -> None:
|
||||
"""Let the BeautifulSoup object know about namespaces encountered
|
||||
while parsing the document.
|
||||
|
||||
This might be useful later on when creating CSS selectors.
|
||||
|
||||
This will track (almost) all namespaces, even ones that were
|
||||
only in scope for part of the document. If two namespaces have
|
||||
the same prefix, only the first one encountered will be
|
||||
tracked. Un-prefixed namespaces are not tracked.
|
||||
|
||||
:param mapping: A dictionary mapping namespace prefixes to URIs.
|
||||
"""
|
||||
assert self.soup is not None
|
||||
for key, value in list(mapping.items()):
|
||||
# This is 'if key' and not 'if key is not None' because we
|
||||
# don't track un-prefixed namespaces. Soupselect will
|
||||
# treat an un-prefixed namespace as the default, which
|
||||
# causes confusion in some cases.
|
||||
if key and key not in self.soup._namespaces:
|
||||
# Let the BeautifulSoup object know about a new namespace.
|
||||
# If there are multiple namespaces defined with the same
|
||||
# prefix, the first one in the document takes precedence.
|
||||
self.soup._namespaces[key] = value
|
||||
|
||||
def default_parser(self, encoding: Optional[_Encoding]) -> _ParserOrParserClass:
|
||||
"""Find the default parser for the given encoding.
|
||||
|
||||
:return: Either a parser object or a class, which
|
||||
will be instantiated with default arguments.
|
||||
"""
|
||||
if self._default_parser is not None:
|
||||
return self._default_parser
|
||||
return self.DEFAULT_PARSER_CLASS(target=self, recover=True, huge_tree=self.huge_tree, encoding=encoding)
|
||||
|
||||
def parser_for(self, encoding: Optional[_Encoding]) -> _LXMLParser:
|
||||
"""Instantiate an appropriate parser for the given encoding.
|
||||
|
||||
:param encoding: A string.
|
||||
:return: A parser object such as an `etree.XMLParser`.
|
||||
"""
|
||||
# Use the default parser.
|
||||
parser = self.default_parser(encoding)
|
||||
|
||||
if callable(parser):
|
||||
# Instantiate the parser with default arguments
|
||||
parser = parser(target=self, recover=True, huge_tree=self.huge_tree, encoding=encoding)
|
||||
return parser
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parser: Optional[etree.XMLParser] = None,
|
||||
empty_element_tags: Optional[Set[str]] = None,
|
||||
huge_tree: bool = False,
|
||||
**kwargs: Any,
|
||||
):
|
||||
# TODO: Issue a warning if parser is present but not a
|
||||
# callable, since that means there's no way to create new
|
||||
# parsers for different encodings.
|
||||
self._default_parser = parser
|
||||
self.soup = None
|
||||
self.nsmaps = [self.DEFAULT_NSMAPS_INVERTED]
|
||||
self.active_namespace_prefixes = [dict(self.DEFAULT_NSMAPS)]
|
||||
if self.is_xml:
|
||||
self.processing_instruction_class = XMLProcessingInstruction
|
||||
else:
|
||||
self.processing_instruction_class = ProcessingInstruction
|
||||
|
||||
if "attribute_dict_class" not in kwargs:
|
||||
kwargs["attribute_dict_class"] = XMLAttributeDict
|
||||
self.huge_tree = huge_tree
|
||||
|
||||
super(LXMLTreeBuilderForXML, self).__init__(**kwargs)
|
||||
|
||||
def _getNsTag(self, tag: str) -> Tuple[Optional[str], str]:
|
||||
# Split the namespace URL out of a fully-qualified lxml tag
|
||||
# name. Copied from lxml's src/lxml/sax.py.
|
||||
if tag[0] == "{" and "}" in tag:
|
||||
namespace, name = tag[1:].split("}", 1)
|
||||
return (namespace, name)
|
||||
return (None, tag)
|
||||
|
||||
def prepare_markup(
|
||||
self,
|
||||
markup: _RawMarkup,
|
||||
user_specified_encoding: Optional[_Encoding] = None,
|
||||
document_declared_encoding: Optional[_Encoding] = None,
|
||||
exclude_encodings: Optional[_Encodings] = None,
|
||||
) -> Iterable[
|
||||
Tuple[Union[str, bytes], Optional[_Encoding], Optional[_Encoding], bool]
|
||||
]:
|
||||
"""Run any preliminary steps necessary to make incoming markup
|
||||
acceptable to the parser.
|
||||
|
||||
lxml really wants to get a bytestring and convert it to
|
||||
Unicode itself. So instead of using UnicodeDammit to convert
|
||||
the bytestring to Unicode using different encodings, this
|
||||
implementation uses EncodingDetector to iterate over the
|
||||
encodings, and tell lxml to try to parse the document as each
|
||||
one in turn.
|
||||
|
||||
:param markup: Some markup -- hopefully a bytestring.
|
||||
:param user_specified_encoding: The user asked to try this encoding.
|
||||
:param document_declared_encoding: The markup itself claims to be
|
||||
in this encoding.
|
||||
:param exclude_encodings: The user asked _not_ to try any of
|
||||
these encodings.
|
||||
|
||||
:yield: A series of 4-tuples: (markup, encoding, declared encoding,
|
||||
has undergone character replacement)
|
||||
|
||||
Each 4-tuple represents a strategy for converting the
|
||||
document to Unicode and parsing it. Each strategy will be tried
|
||||
in turn.
|
||||
"""
|
||||
if not self.is_xml:
|
||||
# We're in HTML mode, so if we're given XML, that's worth
|
||||
# noting.
|
||||
DetectsXMLParsedAsHTML.warn_if_markup_looks_like_xml(markup, stacklevel=3)
|
||||
|
||||
if isinstance(markup, str):
|
||||
# We were given Unicode. Maybe lxml can parse Unicode on
|
||||
# this system?
|
||||
|
||||
# TODO: This is a workaround for
|
||||
# https://bugs.launchpad.net/lxml/+bug/1948551.
|
||||
# We can remove it once the upstream issue is fixed.
|
||||
if len(markup) > 0 and markup[0] == "\N{BYTE ORDER MARK}":
|
||||
markup = markup[1:]
|
||||
yield markup, None, document_declared_encoding, False
|
||||
|
||||
if isinstance(markup, str):
|
||||
# No, apparently not. Convert the Unicode to UTF-8 and
|
||||
# tell lxml to parse it as UTF-8.
|
||||
yield (markup.encode("utf8"), "utf8", document_declared_encoding, False)
|
||||
|
||||
# Since the document was Unicode in the first place, there
|
||||
# is no need to try any more strategies; we know this will
|
||||
# work.
|
||||
return
|
||||
|
||||
known_definite_encodings: List[_Encoding] = []
|
||||
if user_specified_encoding:
|
||||
# This was provided by the end-user; treat it as a known
|
||||
# definite encoding per the algorithm laid out in the
|
||||
# HTML5 spec. (See the EncodingDetector class for
|
||||
# details.)
|
||||
known_definite_encodings.append(user_specified_encoding)
|
||||
|
||||
user_encodings: List[_Encoding] = []
|
||||
if document_declared_encoding:
|
||||
# This was found in the document; treat it as a slightly
|
||||
# lower-priority user encoding.
|
||||
user_encodings.append(document_declared_encoding)
|
||||
|
||||
detector = EncodingDetector(
|
||||
markup,
|
||||
known_definite_encodings=known_definite_encodings,
|
||||
user_encodings=user_encodings,
|
||||
is_html=not self.is_xml,
|
||||
exclude_encodings=exclude_encodings,
|
||||
)
|
||||
for encoding in detector.encodings:
|
||||
yield (detector.markup, encoding, document_declared_encoding, False)
|
||||
|
||||
def feed(self, markup: _RawMarkup) -> None:
|
||||
io: Union[BytesIO, StringIO]
|
||||
if isinstance(markup, bytes):
|
||||
io = BytesIO(markup)
|
||||
elif isinstance(markup, str):
|
||||
io = StringIO(markup)
|
||||
|
||||
# initialize_soup is called before feed, so we know this
|
||||
# is not None.
|
||||
assert self.soup is not None
|
||||
|
||||
# Call feed() at least once, even if the markup is empty,
|
||||
# or the parser won't be initialized.
|
||||
data = io.read(self.CHUNK_SIZE)
|
||||
try:
|
||||
self.parser = self.parser_for(self.soup.original_encoding)
|
||||
self.parser.feed(data)
|
||||
while len(data) != 0:
|
||||
# Now call feed() on the rest of the data, chunk by chunk.
|
||||
data = io.read(self.CHUNK_SIZE)
|
||||
if len(data) != 0:
|
||||
self.parser.feed(data)
|
||||
self.parser.close()
|
||||
except (UnicodeDecodeError, LookupError, etree.ParserError) as e:
|
||||
raise ParserRejectedMarkup(e)
|
||||
|
||||
def close(self) -> None:
|
||||
self.nsmaps = [self.DEFAULT_NSMAPS_INVERTED]
|
||||
|
||||
def start(
|
||||
self,
|
||||
tag: str | bytes,
|
||||
attrib: Dict[str | bytes, str | bytes],
|
||||
nsmap: _NamespaceMapping = {},
|
||||
) -> None:
|
||||
# This is called by lxml code as a result of calling
|
||||
# BeautifulSoup.feed(), and we know self.soup is set by the time feed()
|
||||
# is called.
|
||||
assert self.soup is not None
|
||||
assert isinstance(tag, str)
|
||||
|
||||
# We need to recreate the attribute dict for three
|
||||
# reasons. First, for type checking, so we can assert there
|
||||
# are no bytestrings in the keys or values. Second, because we
|
||||
# need a mutable dict--lxml might send us an immutable
|
||||
# dictproxy. Third, so we can handle namespaced attribute
|
||||
# names by converting the keys to NamespacedAttributes.
|
||||
new_attrib: Dict[Union[str, NamespacedAttribute], str] = (
|
||||
self.attribute_dict_class()
|
||||
)
|
||||
for k, v in attrib.items():
|
||||
assert isinstance(k, str)
|
||||
assert isinstance(v, str)
|
||||
new_attrib[k] = v
|
||||
|
||||
nsprefix: Optional[_NamespacePrefix] = None
|
||||
namespace: Optional[_NamespaceURL] = None
|
||||
# Invert each namespace map as it comes in.
|
||||
if len(nsmap) == 0 and len(self.nsmaps) > 1:
|
||||
# There are no new namespaces for this tag, but
|
||||
# non-default namespaces are in play, so we need a
|
||||
# separate tag stack to know when they end.
|
||||
self.nsmaps.append(None)
|
||||
elif len(nsmap) > 0:
|
||||
# A new namespace mapping has come into play.
|
||||
|
||||
# First, Let the BeautifulSoup object know about it.
|
||||
self._register_namespaces(nsmap)
|
||||
|
||||
# Then, add it to our running list of inverted namespace
|
||||
# mappings.
|
||||
self.nsmaps.append(_invert(nsmap))
|
||||
|
||||
# The currently active namespace prefixes have
|
||||
# changed. Calculate the new mapping so it can be stored
|
||||
# with all Tag objects created while these prefixes are in
|
||||
# scope.
|
||||
current_mapping = dict(self.active_namespace_prefixes[-1])
|
||||
current_mapping.update(nsmap)
|
||||
|
||||
# We should not track un-prefixed namespaces as we can only hold one
|
||||
# and it will be recognized as the default namespace by soupsieve,
|
||||
# which may be confusing in some situations.
|
||||
if "" in current_mapping:
|
||||
del current_mapping[""]
|
||||
self.active_namespace_prefixes.append(current_mapping)
|
||||
|
||||
# Also treat the namespace mapping as a set of attributes on the
|
||||
# tag, so we can recreate it later.
|
||||
for prefix, namespace in list(nsmap.items()):
|
||||
attribute = NamespacedAttribute(
|
||||
"xmlns", prefix, "http://www.w3.org/2000/xmlns/"
|
||||
)
|
||||
new_attrib[attribute] = namespace
|
||||
|
||||
# Namespaces are in play. Find any attributes that came in
|
||||
# from lxml with namespaces attached to their names, and
|
||||
# turn then into NamespacedAttribute objects.
|
||||
final_attrib: AttributeDict = self.attribute_dict_class()
|
||||
for attr, value in list(new_attrib.items()):
|
||||
namespace, attr = self._getNsTag(attr)
|
||||
if namespace is None:
|
||||
final_attrib[attr] = value
|
||||
else:
|
||||
nsprefix = self._prefix_for_namespace(namespace)
|
||||
attr = NamespacedAttribute(nsprefix, attr, namespace)
|
||||
final_attrib[attr] = value
|
||||
|
||||
namespace, tag = self._getNsTag(tag)
|
||||
nsprefix = self._prefix_for_namespace(namespace)
|
||||
self.soup.handle_starttag(
|
||||
tag,
|
||||
namespace,
|
||||
nsprefix,
|
||||
final_attrib,
|
||||
namespaces=self.active_namespace_prefixes[-1],
|
||||
)
|
||||
|
||||
def _prefix_for_namespace(
|
||||
self, namespace: Optional[_NamespaceURL]
|
||||
) -> Optional[_NamespacePrefix]:
|
||||
"""Find the currently active prefix for the given namespace."""
|
||||
if namespace is None:
|
||||
return None
|
||||
for inverted_nsmap in reversed(self.nsmaps):
|
||||
if inverted_nsmap is not None and namespace in inverted_nsmap:
|
||||
return inverted_nsmap[namespace]
|
||||
return None
|
||||
|
||||
def end(self, tag: str | bytes) -> None:
|
||||
assert self.soup is not None
|
||||
assert isinstance(tag, str)
|
||||
self.soup.endData()
|
||||
namespace, tag = self._getNsTag(tag)
|
||||
nsprefix = None
|
||||
if namespace is not None:
|
||||
for inverted_nsmap in reversed(self.nsmaps):
|
||||
if inverted_nsmap is not None and namespace in inverted_nsmap:
|
||||
nsprefix = inverted_nsmap[namespace]
|
||||
break
|
||||
self.soup.handle_endtag(tag, nsprefix)
|
||||
if len(self.nsmaps) > 1:
|
||||
# This tag, or one of its parents, introduced a namespace
|
||||
# mapping, so pop it off the stack.
|
||||
out_of_scope_nsmap = self.nsmaps.pop()
|
||||
|
||||
if out_of_scope_nsmap is not None:
|
||||
# This tag introduced a namespace mapping which is no
|
||||
# longer in scope. Recalculate the currently active
|
||||
# namespace prefixes.
|
||||
self.active_namespace_prefixes.pop()
|
||||
|
||||
def pi(self, target: str, data: str) -> None:
|
||||
assert self.soup is not None
|
||||
self.soup.endData()
|
||||
data = target + " " + data
|
||||
self.soup.handle_data(data)
|
||||
self.soup.endData(self.processing_instruction_class)
|
||||
|
||||
def data(self, data: str | bytes) -> None:
|
||||
assert self.soup is not None
|
||||
assert isinstance(data, str)
|
||||
self.soup.handle_data(data)
|
||||
|
||||
def doctype(self, name: str, pubid: str, system: str) -> None:
|
||||
assert self.soup is not None
|
||||
self.soup.endData()
|
||||
doctype_string = Doctype._string_for_name_and_ids(name, pubid, system)
|
||||
self.soup.handle_data(doctype_string)
|
||||
self.soup.endData(containerClass=Doctype)
|
||||
|
||||
def comment(self, text: str | bytes) -> None:
|
||||
"Handle comments as Comment objects."
|
||||
assert self.soup is not None
|
||||
assert isinstance(text, str)
|
||||
self.soup.endData()
|
||||
self.soup.handle_data(text)
|
||||
self.soup.endData(Comment)
|
||||
|
||||
def test_fragment_to_document(self, fragment: str) -> str:
|
||||
"""See `TreeBuilder`."""
|
||||
return '<?xml version="1.0" encoding="utf-8"?>\n%s' % fragment
|
||||
|
||||
|
||||
class LXMLTreeBuilder(HTMLTreeBuilder, LXMLTreeBuilderForXML):
|
||||
NAME: str = LXML
|
||||
ALTERNATE_NAMES: Iterable[str] = ["lxml-html"]
|
||||
|
||||
features: Iterable[str] = list(ALTERNATE_NAMES) + [NAME, HTML, FAST, PERMISSIVE]
|
||||
is_xml: bool = False
|
||||
|
||||
def default_parser(self, encoding: Optional[_Encoding]) -> _ParserOrParserClass:
|
||||
return etree.HTMLParser
|
||||
|
||||
def feed(self, markup: _RawMarkup) -> None:
|
||||
# We know self.soup is set by the time feed() is called.
|
||||
assert self.soup is not None
|
||||
encoding = self.soup.original_encoding
|
||||
try:
|
||||
self.parser = self.parser_for(encoding)
|
||||
self.parser.feed(markup)
|
||||
self.parser.close()
|
||||
except (UnicodeDecodeError, LookupError, etree.ParserError) as e:
|
||||
raise ParserRejectedMarkup(e)
|
||||
|
||||
def test_fragment_to_document(self, fragment: str) -> str:
|
||||
"""See `TreeBuilder`."""
|
||||
return "<html><body>%s</body></html>" % fragment
|
||||
Vendored
+339
@@ -0,0 +1,339 @@
|
||||
"""Integration code for CSS selectors using `Soup Sieve <https://facelessuser.github.io/soupsieve/>`_ (pypi: ``soupsieve``).
|
||||
|
||||
Acquire a `CSS` object through the `element.Tag.css` attribute of
|
||||
the starting point of your CSS selector, or (if you want to run a
|
||||
selector against the entire document) of the `BeautifulSoup` object
|
||||
itself.
|
||||
|
||||
The main advantage of doing this instead of using ``soupsieve``
|
||||
functions is that you don't need to keep passing the `element.Tag` to be
|
||||
selected against, since the `CSS` object is permanently scoped to that
|
||||
`element.Tag`.
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import ModuleType
|
||||
from typing import (
|
||||
Any,
|
||||
cast,
|
||||
Iterable,
|
||||
Iterator,
|
||||
MutableSequence,
|
||||
Optional,
|
||||
TYPE_CHECKING,
|
||||
)
|
||||
import warnings
|
||||
from bs4._typing import _NamespaceMapping
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from soupsieve import SoupSieve
|
||||
from bs4 import element
|
||||
from bs4.element import ResultSet, Tag
|
||||
|
||||
soupsieve: Optional[ModuleType]
|
||||
try:
|
||||
import soupsieve
|
||||
except ImportError:
|
||||
soupsieve = None
|
||||
warnings.warn(
|
||||
"The soupsieve package is not installed. CSS selectors cannot be used."
|
||||
)
|
||||
|
||||
|
||||
class CSS(object):
|
||||
"""A proxy object against the ``soupsieve`` library, to simplify its
|
||||
CSS selector API.
|
||||
|
||||
You don't need to instantiate this class yourself; instead, use
|
||||
`element.Tag.css`.
|
||||
|
||||
:param tag: All CSS selectors run by this object will use this as
|
||||
their starting point.
|
||||
|
||||
:param api: An optional drop-in replacement for the ``soupsieve`` module,
|
||||
intended for use in unit tests.
|
||||
"""
|
||||
|
||||
def __init__(self, tag: element.Tag, api: Optional[ModuleType] = None):
|
||||
if api is None:
|
||||
api = soupsieve
|
||||
if api is None:
|
||||
raise NotImplementedError(
|
||||
"Cannot execute CSS selectors because the soupsieve package is not installed."
|
||||
)
|
||||
self.api = api
|
||||
self.tag = tag
|
||||
|
||||
def escape(self, ident: str) -> str:
|
||||
"""Escape a CSS identifier.
|
||||
|
||||
This is a simple wrapper around `soupsieve.escape() <https://facelessuser.github.io/soupsieve/api/#soupsieveescape>`_. See the
|
||||
documentation for that function for more information.
|
||||
"""
|
||||
if soupsieve is None:
|
||||
raise NotImplementedError(
|
||||
"Cannot escape CSS identifiers because the soupsieve package is not installed."
|
||||
)
|
||||
return cast(str, self.api.escape(ident))
|
||||
|
||||
def _ns(
|
||||
self, ns: Optional[_NamespaceMapping], select: str
|
||||
) -> Optional[_NamespaceMapping]:
|
||||
"""Normalize a dictionary of namespaces."""
|
||||
if not isinstance(select, self.api.SoupSieve) and ns is None:
|
||||
# If the selector is a precompiled pattern, it already has
|
||||
# a namespace context compiled in, which cannot be
|
||||
# replaced.
|
||||
ns = self.tag._namespaces
|
||||
return ns
|
||||
|
||||
def _rs(self, results: MutableSequence[Tag]) -> ResultSet[Tag]:
|
||||
"""Normalize a list of results to a py:class:`ResultSet`.
|
||||
|
||||
A py:class:`ResultSet` is more consistent with the rest of
|
||||
Beautiful Soup's API, and :py:meth:`ResultSet.__getattr__` has
|
||||
a helpful error message if you try to treat a list of results
|
||||
as a single result (a common mistake).
|
||||
"""
|
||||
# Import here to avoid circular import
|
||||
from bs4 import ResultSet
|
||||
|
||||
return ResultSet(None, results)
|
||||
|
||||
def compile(
|
||||
self,
|
||||
select: str,
|
||||
namespaces: Optional[_NamespaceMapping] = None,
|
||||
flags: int = 0,
|
||||
**kwargs: Any,
|
||||
) -> SoupSieve:
|
||||
"""Pre-compile a selector and return the compiled object.
|
||||
|
||||
:param selector: A CSS selector.
|
||||
|
||||
:param namespaces: A dictionary mapping namespace prefixes
|
||||
used in the CSS selector to namespace URIs. By default,
|
||||
Beautiful Soup will use the prefixes it encountered while
|
||||
parsing the document.
|
||||
|
||||
:param flags: Flags to be passed into Soup Sieve's
|
||||
`soupsieve.compile() <https://facelessuser.github.io/soupsieve/api/#soupsievecompile>`_ method.
|
||||
|
||||
:param kwargs: Keyword arguments to be passed into Soup Sieve's
|
||||
`soupsieve.compile() <https://facelessuser.github.io/soupsieve/api/#soupsievecompile>`_ method.
|
||||
|
||||
:return: A precompiled selector object.
|
||||
:rtype: soupsieve.SoupSieve
|
||||
"""
|
||||
return self.api.compile(select, self._ns(namespaces, select), flags, **kwargs)
|
||||
|
||||
def select_one(
|
||||
self,
|
||||
select: str,
|
||||
namespaces: Optional[_NamespaceMapping] = None,
|
||||
flags: int = 0,
|
||||
**kwargs: Any,
|
||||
) -> element.Tag | None:
|
||||
"""Perform a CSS selection operation on the current Tag and return the
|
||||
first result, if any.
|
||||
|
||||
This uses the Soup Sieve library. For more information, see
|
||||
that library's documentation for the `soupsieve.select_one() <https://facelessuser.github.io/soupsieve/api/#soupsieveselect_one>`_ method.
|
||||
|
||||
:param selector: A CSS selector.
|
||||
|
||||
:param namespaces: A dictionary mapping namespace prefixes
|
||||
used in the CSS selector to namespace URIs. By default,
|
||||
Beautiful Soup will use the prefixes it encountered while
|
||||
parsing the document.
|
||||
|
||||
:param flags: Flags to be passed into Soup Sieve's
|
||||
`soupsieve.select_one() <https://facelessuser.github.io/soupsieve/api/#soupsieveselect_one>`_ method.
|
||||
|
||||
:param kwargs: Keyword arguments to be passed into Soup Sieve's
|
||||
`soupsieve.select_one() <https://facelessuser.github.io/soupsieve/api/#soupsieveselect_one>`_ method.
|
||||
"""
|
||||
return self.api.select_one(
|
||||
select, self.tag, self._ns(namespaces, select), flags, **kwargs
|
||||
)
|
||||
|
||||
def select(
|
||||
self,
|
||||
select: str,
|
||||
namespaces: Optional[_NamespaceMapping] = None,
|
||||
limit: int = 0,
|
||||
flags: int = 0,
|
||||
**kwargs: Any,
|
||||
) -> ResultSet[element.Tag]:
|
||||
"""Perform a CSS selection operation on the current `element.Tag`.
|
||||
|
||||
This uses the Soup Sieve library. For more information, see
|
||||
that library's documentation for the `soupsieve.select() <https://facelessuser.github.io/soupsieve/api/#soupsieveselect>`_ method.
|
||||
|
||||
:param selector: A CSS selector.
|
||||
|
||||
:param namespaces: A dictionary mapping namespace prefixes
|
||||
used in the CSS selector to namespace URIs. By default,
|
||||
Beautiful Soup will pass in the prefixes it encountered while
|
||||
parsing the document.
|
||||
|
||||
:param limit: After finding this number of results, stop looking.
|
||||
|
||||
:param flags: Flags to be passed into Soup Sieve's
|
||||
`soupsieve.select() <https://facelessuser.github.io/soupsieve/api/#soupsieveselect>`_ method.
|
||||
|
||||
:param kwargs: Keyword arguments to be passed into Soup Sieve's
|
||||
`soupsieve.select() <https://facelessuser.github.io/soupsieve/api/#soupsieveselect>`_ method.
|
||||
"""
|
||||
if limit is None:
|
||||
limit = 0
|
||||
|
||||
return self._rs(
|
||||
self.api.select(
|
||||
select, self.tag, self._ns(namespaces, select), limit, flags, **kwargs
|
||||
)
|
||||
)
|
||||
|
||||
def iselect(
|
||||
self,
|
||||
select: str,
|
||||
namespaces: Optional[_NamespaceMapping] = None,
|
||||
limit: int = 0,
|
||||
flags: int = 0,
|
||||
**kwargs: Any,
|
||||
) -> Iterator[element.Tag]:
|
||||
"""Perform a CSS selection operation on the current `element.Tag`.
|
||||
|
||||
This uses the Soup Sieve library. For more information, see
|
||||
that library's documentation for the `soupsieve.iselect()
|
||||
<https://facelessuser.github.io/soupsieve/api/#soupsieveiselect>`_
|
||||
method. It is the same as select(), but it returns a generator
|
||||
instead of a list.
|
||||
|
||||
:param selector: A string containing a CSS selector.
|
||||
|
||||
:param namespaces: A dictionary mapping namespace prefixes
|
||||
used in the CSS selector to namespace URIs. By default,
|
||||
Beautiful Soup will pass in the prefixes it encountered while
|
||||
parsing the document.
|
||||
|
||||
:param limit: After finding this number of results, stop looking.
|
||||
|
||||
:param flags: Flags to be passed into Soup Sieve's
|
||||
`soupsieve.iselect() <https://facelessuser.github.io/soupsieve/api/#soupsieveiselect>`_ method.
|
||||
|
||||
:param kwargs: Keyword arguments to be passed into Soup Sieve's
|
||||
`soupsieve.iselect() <https://facelessuser.github.io/soupsieve/api/#soupsieveiselect>`_ method.
|
||||
"""
|
||||
return self.api.iselect(
|
||||
select, self.tag, self._ns(namespaces, select), limit, flags, **kwargs
|
||||
)
|
||||
|
||||
def closest(
|
||||
self,
|
||||
select: str,
|
||||
namespaces: Optional[_NamespaceMapping] = None,
|
||||
flags: int = 0,
|
||||
**kwargs: Any,
|
||||
) -> Optional[element.Tag]:
|
||||
"""Find the `element.Tag` closest to this one that matches the given selector.
|
||||
|
||||
This uses the Soup Sieve library. For more information, see
|
||||
that library's documentation for the `soupsieve.closest()
|
||||
<https://facelessuser.github.io/soupsieve/api/#soupsieveclosest>`_
|
||||
method.
|
||||
|
||||
:param selector: A string containing a CSS selector.
|
||||
|
||||
:param namespaces: A dictionary mapping namespace prefixes
|
||||
used in the CSS selector to namespace URIs. By default,
|
||||
Beautiful Soup will pass in the prefixes it encountered while
|
||||
parsing the document.
|
||||
|
||||
:param flags: Flags to be passed into Soup Sieve's
|
||||
`soupsieve.closest() <https://facelessuser.github.io/soupsieve/api/#soupsieveclosest>`_ method.
|
||||
|
||||
:param kwargs: Keyword arguments to be passed into Soup Sieve's
|
||||
`soupsieve.closest() <https://facelessuser.github.io/soupsieve/api/#soupsieveclosest>`_ method.
|
||||
|
||||
"""
|
||||
return self.api.closest(
|
||||
select, self.tag, self._ns(namespaces, select), flags, **kwargs
|
||||
)
|
||||
|
||||
def match(
|
||||
self,
|
||||
select: str,
|
||||
namespaces: Optional[_NamespaceMapping] = None,
|
||||
flags: int = 0,
|
||||
**kwargs: Any,
|
||||
) -> bool:
|
||||
"""Check whether or not this `element.Tag` matches the given CSS selector.
|
||||
|
||||
This uses the Soup Sieve library. For more information, see
|
||||
that library's documentation for the `soupsieve.match()
|
||||
<https://facelessuser.github.io/soupsieve/api/#soupsievematch>`_
|
||||
method.
|
||||
|
||||
:param: a CSS selector.
|
||||
|
||||
:param namespaces: A dictionary mapping namespace prefixes
|
||||
used in the CSS selector to namespace URIs. By default,
|
||||
Beautiful Soup will pass in the prefixes it encountered while
|
||||
parsing the document.
|
||||
|
||||
:param flags: Flags to be passed into Soup Sieve's
|
||||
`soupsieve.match()
|
||||
<https://facelessuser.github.io/soupsieve/api/#soupsievematch>`_
|
||||
method.
|
||||
|
||||
:param kwargs: Keyword arguments to be passed into SoupSieve's
|
||||
`soupsieve.match()
|
||||
<https://facelessuser.github.io/soupsieve/api/#soupsievematch>`_
|
||||
method.
|
||||
"""
|
||||
return cast(
|
||||
bool,
|
||||
self.api.match(
|
||||
select, self.tag, self._ns(namespaces, select), flags, **kwargs
|
||||
),
|
||||
)
|
||||
|
||||
def filter(
|
||||
self,
|
||||
select: str,
|
||||
namespaces: Optional[_NamespaceMapping] = None,
|
||||
flags: int = 0,
|
||||
**kwargs: Any,
|
||||
) -> ResultSet[element.Tag]:
|
||||
"""Filter this `element.Tag`'s direct children based on the given CSS selector.
|
||||
|
||||
This uses the Soup Sieve library. It works the same way as
|
||||
passing a `element.Tag` into that library's `soupsieve.filter()
|
||||
<https://facelessuser.github.io/soupsieve/api/#soupsievefilter>`_
|
||||
method. For more information, see the documentation for
|
||||
`soupsieve.filter()
|
||||
<https://facelessuser.github.io/soupsieve/api/#soupsievefilter>`_.
|
||||
|
||||
:param namespaces: A dictionary mapping namespace prefixes
|
||||
used in the CSS selector to namespace URIs. By default,
|
||||
Beautiful Soup will pass in the prefixes it encountered while
|
||||
parsing the document.
|
||||
|
||||
:param flags: Flags to be passed into Soup Sieve's
|
||||
`soupsieve.filter()
|
||||
<https://facelessuser.github.io/soupsieve/api/#soupsievefilter>`_
|
||||
method.
|
||||
|
||||
:param kwargs: Keyword arguments to be passed into SoupSieve's
|
||||
`soupsieve.filter()
|
||||
<https://facelessuser.github.io/soupsieve/api/#soupsievefilter>`_
|
||||
method.
|
||||
"""
|
||||
return self._rs(
|
||||
self.api.filter(
|
||||
select, self.tag, self._ns(namespaces, select), flags, **kwargs
|
||||
)
|
||||
)
|
||||
+1525
File diff suppressed because it is too large.
Load diff
+268
@@ -0,0 +1,268 @@
|
||||
"""Diagnostic functions, mainly for use when doing tech support."""
|
||||
|
||||
# Use of this source code is governed by the MIT license.
|
||||
__license__ = "MIT"
|
||||
|
||||
import cProfile
|
||||
from io import BytesIO
|
||||
from html.parser import HTMLParser
|
||||
import bs4
|
||||
from bs4 import BeautifulSoup, __version__
|
||||
from bs4.builder import builder_registry
|
||||
from typing import (
|
||||
Any,
|
||||
IO,
|
||||
List,
|
||||
Optional,
|
||||
Tuple,
|
||||
TYPE_CHECKING,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from bs4._typing import _IncomingMarkup
|
||||
|
||||
import pstats
|
||||
import random
|
||||
import tempfile
|
||||
import time
|
||||
import traceback
|
||||
import sys
|
||||
|
||||
|
||||
def diagnose(data: "_IncomingMarkup") -> None:
|
||||
"""Diagnostic suite for isolating common problems.
|
||||
|
||||
:param data: Some markup that needs to be explained.
|
||||
:return: None; diagnostics are printed to standard output.
|
||||
"""
|
||||
print(("Diagnostic running on Beautiful Soup %s" % __version__))
|
||||
print(("Python version %s" % sys.version))
|
||||
|
||||
basic_parsers = ["html.parser", "html5lib", "lxml"]
|
||||
for name in basic_parsers:
|
||||
for builder in builder_registry.builders:
|
||||
if name in builder.features:
|
||||
break
|
||||
else:
|
||||
basic_parsers.remove(name)
|
||||
print(
|
||||
("I noticed that %s is not installed. Installing it may help." % name)
|
||||
)
|
||||
|
||||
if "lxml" in basic_parsers:
|
||||
basic_parsers.append("lxml-xml")
|
||||
try:
|
||||
from lxml import etree # type:ignore
|
||||
|
||||
print(("Found lxml version %s" % ".".join(map(str, etree.LXML_VERSION))))
|
||||
except ImportError:
|
||||
print("lxml is not installed or couldn't be imported.")
|
||||
|
||||
if "html5lib" in basic_parsers:
|
||||
try:
|
||||
import html5lib
|
||||
|
||||
print(("Found html5lib version %s" % html5lib.__version__))
|
||||
except ImportError:
|
||||
print("html5lib is not installed or couldn't be imported.")
|
||||
|
||||
if hasattr(data, "read"):
|
||||
data = data.read()
|
||||
|
||||
for parser in basic_parsers:
|
||||
print(("Trying to parse your markup with %s" % parser))
|
||||
success = False
|
||||
try:
|
||||
soup = BeautifulSoup(data, features=parser)
|
||||
success = True
|
||||
except Exception:
|
||||
print(("%s could not parse the markup." % parser))
|
||||
traceback.print_exc()
|
||||
if success:
|
||||
print(("Here's what %s did with the markup:" % parser))
|
||||
print((soup.prettify()))
|
||||
|
||||
print(("-" * 80))
|
||||
|
||||
|
||||
def lxml_trace(data: "_IncomingMarkup", html: bool = True, **kwargs: Any) -> None:
|
||||
"""Print out the lxml events that occur during parsing.
|
||||
|
||||
This lets you see how lxml parses a document when no Beautiful
|
||||
Soup code is running. You can use this to determine whether
|
||||
an lxml-specific problem is in Beautiful Soup's lxml tree builders
|
||||
or in lxml itself.
|
||||
|
||||
:param data: Some markup.
|
||||
:param html: If True, markup will be parsed with lxml's HTML parser.
|
||||
if False, lxml's XML parser will be used.
|
||||
"""
|
||||
from lxml import etree
|
||||
|
||||
recover = kwargs.pop("recover", True)
|
||||
if isinstance(data, str):
|
||||
data = data.encode("utf8")
|
||||
if not isinstance(data, IO):
|
||||
reader = BytesIO(data)
|
||||
for event, element in etree.iterparse(reader, html=html, recover=recover, **kwargs):
|
||||
print(("%s, %4s, %s" % (event, element.tag, element.text)))
|
||||
|
||||
|
||||
class AnnouncingParser(HTMLParser):
|
||||
"""Subclass of HTMLParser that announces parse events, without doing
|
||||
anything else.
|
||||
|
||||
You can use this to get a picture of how html.parser sees a given
|
||||
document. The easiest way to do this is to call `htmlparser_trace`.
|
||||
"""
|
||||
|
||||
def _p(self, s: str) -> None:
|
||||
print(s)
|
||||
|
||||
def handle_starttag(
|
||||
self,
|
||||
name: str,
|
||||
attrs: List[Tuple[str, Optional[str]]],
|
||||
handle_empty_element: bool = True,
|
||||
) -> None:
|
||||
self._p(f"{name} {attrs} START")
|
||||
|
||||
def handle_endtag(self, name: str, check_already_closed: bool = True) -> None:
|
||||
self._p("%s END" % name)
|
||||
|
||||
def handle_data(self, data: str) -> None:
|
||||
self._p("%s DATA" % data)
|
||||
|
||||
def handle_charref(self, name: str) -> None:
|
||||
self._p("%s CHARREF" % name)
|
||||
|
||||
def handle_entityref(self, name: str) -> None:
|
||||
self._p("%s ENTITYREF" % name)
|
||||
|
||||
def handle_comment(self, data: str) -> None:
|
||||
self._p("%s COMMENT" % data)
|
||||
|
||||
def handle_decl(self, data: str) -> None:
|
||||
self._p("%s DECL" % data)
|
||||
|
||||
def unknown_decl(self, data: str) -> None:
|
||||
self._p("%s UNKNOWN-DECL" % data)
|
||||
|
||||
def handle_pi(self, data: str) -> None:
|
||||
self._p("%s PI" % data)
|
||||
|
||||
|
||||
def htmlparser_trace(data: str) -> None:
|
||||
"""Print out the HTMLParser events that occur during parsing.
|
||||
|
||||
This lets you see how HTMLParser parses a document when no
|
||||
Beautiful Soup code is running.
|
||||
|
||||
:param data: Some markup.
|
||||
"""
|
||||
parser = AnnouncingParser()
|
||||
parser.feed(data)
|
||||
|
||||
|
||||
_vowels: str = "aeiou"
|
||||
_consonants: str = "bcdfghjklmnpqrstvwxyz"
|
||||
|
||||
|
||||
def rword(length: int = 5) -> str:
|
||||
"""Generate a random word-like string.
|
||||
|
||||
:meta private:
|
||||
"""
|
||||
s = ""
|
||||
for i in range(length):
|
||||
if i % 2 == 0:
|
||||
t = _consonants
|
||||
else:
|
||||
t = _vowels
|
||||
s += random.choice(t)
|
||||
return s
|
||||
|
||||
|
||||
def rsentence(length: int = 4) -> str:
|
||||
"""Generate a random sentence-like string.
|
||||
|
||||
:meta private:
|
||||
"""
|
||||
return " ".join(rword(random.randint(4, 9)) for i in range(length))
|
||||
|
||||
|
||||
def rdoc(num_elements: int = 1000) -> str:
|
||||
"""Randomly generate an invalid HTML document.
|
||||
|
||||
:meta private:
|
||||
"""
|
||||
tag_names = ["p", "div", "span", "i", "b", "script", "table"]
|
||||
elements = []
|
||||
for i in range(num_elements):
|
||||
choice = random.randint(0, 3)
|
||||
if choice == 0:
|
||||
# New tag.
|
||||
tag_name = random.choice(tag_names)
|
||||
elements.append("<%s>" % tag_name)
|
||||
elif choice == 1:
|
||||
elements.append(rsentence(random.randint(1, 4)))
|
||||
elif choice == 2:
|
||||
# Close a tag.
|
||||
tag_name = random.choice(tag_names)
|
||||
elements.append("</%s>" % tag_name)
|
||||
return "<html>" + "\n".join(elements) + "</html>"
|
||||
|
||||
|
||||
def benchmark_parsers(num_elements: int = 100000) -> None:
|
||||
"""Very basic head-to-head performance benchmark."""
|
||||
print(("Comparative parser benchmark on Beautiful Soup %s" % __version__))
|
||||
data = rdoc(num_elements)
|
||||
print(("Generated a large invalid HTML document (%d bytes)." % len(data)))
|
||||
|
||||
for parser_name in ["lxml", ["lxml", "html"], "html5lib", "html.parser"]:
|
||||
success = False
|
||||
try:
|
||||
a = time.time()
|
||||
BeautifulSoup(data, parser_name)
|
||||
b = time.time()
|
||||
success = True
|
||||
except Exception:
|
||||
print(("%s could not parse the markup." % parser_name))
|
||||
traceback.print_exc()
|
||||
if success:
|
||||
print(("BS4+%s parsed the markup in %.2fs." % (parser_name, b - a)))
|
||||
|
||||
from lxml import etree
|
||||
|
||||
a = time.time()
|
||||
etree.HTML(data)
|
||||
b = time.time()
|
||||
print(("Raw lxml parsed the markup in %.2fs." % (b - a)))
|
||||
|
||||
import html5lib
|
||||
|
||||
parser = html5lib.HTMLParser()
|
||||
a = time.time()
|
||||
parser.parse(data)
|
||||
b = time.time()
|
||||
print(("Raw html5lib parsed the markup in %.2fs." % (b - a)))
|
||||
|
||||
|
||||
def profile(num_elements: int = 100000, parser: str = "lxml") -> None:
|
||||
"""Use Python's profiler on a randomly generated document."""
|
||||
filehandle = tempfile.NamedTemporaryFile()
|
||||
filename = filehandle.name
|
||||
|
||||
data = rdoc(num_elements)
|
||||
vars = dict(bs4=bs4, data=data, parser=parser)
|
||||
cProfile.runctx("bs4.BeautifulSoup(data, parser)", vars, vars, filename)
|
||||
|
||||
stats = pstats.Stats(filename)
|
||||
# stats.strip_dirs()
|
||||
stats.sort_stats("cumulative")
|
||||
stats.print_stats("_html5lib|bs4", 50)
|
||||
|
||||
|
||||
# If this file is run as a script, standard input is diagnosed.
|
||||
if __name__ == "__main__":
|
||||
diagnose(sys.stdin.read())
|
||||
+3395
File diff suppressed because it is too large.
Load diff
+28
@@ -0,0 +1,28 @@
|
||||
"""Exceptions defined by Beautiful Soup itself."""
|
||||
|
||||
from typing import Union
|
||||
|
||||
|
||||
class StopParsing(Exception):
|
||||
"""Exception raised by a TreeBuilder if it's unable to continue parsing."""
|
||||
|
||||
|
||||
class FeatureNotFound(ValueError):
|
||||
"""Exception raised by the BeautifulSoup constructor if no parser with the
|
||||
requested features is found.
|
||||
"""
|
||||
|
||||
|
||||
class ParserRejectedMarkup(Exception):
|
||||
"""An Exception to be raised when the underlying parser simply
|
||||
refuses to parse the given markup.
|
||||
"""
|
||||
|
||||
def __init__(self, message_or_exception: Union[str, Exception]):
|
||||
"""Explain why the parser rejected the given markup, either
|
||||
with a textual explanation or another exception.
|
||||
"""
|
||||
if isinstance(message_or_exception, Exception):
|
||||
e = message_or_exception
|
||||
message_or_exception = "%s: %s" % (e.__class__.__name__, str(e))
|
||||
super(ParserRejectedMarkup, self).__init__(message_or_exception)
|
||||
+764
@@ -0,0 +1,764 @@
|
||||
from __future__ import annotations
|
||||
from collections import defaultdict
|
||||
import re
|
||||
from typing import (
|
||||
Any,
|
||||
Callable,
|
||||
cast,
|
||||
Dict,
|
||||
Iterator,
|
||||
Iterable,
|
||||
List,
|
||||
Optional,
|
||||
Sequence,
|
||||
Type,
|
||||
Union,
|
||||
)
|
||||
import warnings
|
||||
|
||||
from bs4._deprecation import _deprecated
|
||||
from bs4.element import (
|
||||
AttributeDict,
|
||||
NavigableString,
|
||||
PageElement,
|
||||
ResultSet,
|
||||
Tag,
|
||||
)
|
||||
from bs4._typing import (
|
||||
_AtMostOneElement,
|
||||
_AttributeValue,
|
||||
_NullableStringMatchFunction,
|
||||
_OneElement,
|
||||
_PageElementMatchFunction,
|
||||
_QueryResults,
|
||||
_RawAttributeValues,
|
||||
_RegularExpressionProtocol,
|
||||
_StrainableAttribute,
|
||||
_StrainableElement,
|
||||
_StrainableString,
|
||||
_StringMatchFunction,
|
||||
_TagMatchFunction,
|
||||
)
|
||||
|
||||
|
||||
class ElementFilter(object):
|
||||
"""`ElementFilter` encapsulates the logic necessary to decide:
|
||||
|
||||
1. whether a `PageElement` (a `Tag` or a `NavigableString`) matches a
|
||||
user-specified query.
|
||||
|
||||
2. whether a given sequence of markup found during initial parsing
|
||||
should be turned into a `PageElement` at all, or simply discarded.
|
||||
|
||||
The base class is the simplest `ElementFilter`. By default, it
|
||||
matches everything and allows all markup to become `PageElement`
|
||||
objects. You can make it more selective by passing in a
|
||||
user-defined match function, or defining a subclass.
|
||||
|
||||
Most users of Beautiful Soup will never need to use
|
||||
`ElementFilter`, or its more capable subclass
|
||||
`SoupStrainer`. Instead, they will use methods like
|
||||
:py:meth:`Tag.find`, which will convert their arguments into
|
||||
`SoupStrainer` objects and run them against the tree.
|
||||
|
||||
However, if you find yourself wanting to treat the arguments to
|
||||
Beautiful Soup's find_*() methods as first-class objects, those
|
||||
objects will be `SoupStrainer` objects. You can create them
|
||||
yourself and then make use of functions like
|
||||
`ElementFilter.filter()`.
|
||||
"""
|
||||
|
||||
match_function: Optional[_PageElementMatchFunction]
|
||||
|
||||
def __init__(self, match_function: Optional[_PageElementMatchFunction] = None):
|
||||
"""Pass in a match function to easily customize the behavior of
|
||||
`ElementFilter.match` without needing to subclass.
|
||||
|
||||
:param match_function: A function that takes a `PageElement`
|
||||
and returns `True` if that `PageElement` matches some criteria.
|
||||
"""
|
||||
self.match_function = match_function
|
||||
|
||||
@property
|
||||
def includes_everything(self) -> bool:
|
||||
"""Does this `ElementFilter` obviously include everything? If so,
|
||||
the filter process can be made much faster.
|
||||
|
||||
The `ElementFilter` might turn out to include everything even
|
||||
if this returns `False`, but it won't include everything in an
|
||||
obvious way.
|
||||
|
||||
The base `ElementFilter` implementation includes things based on
|
||||
the match function, so includes_everything is only true if
|
||||
there is no match function.
|
||||
"""
|
||||
return not self.match_function
|
||||
|
||||
@property
|
||||
def excludes_everything(self) -> bool:
|
||||
"""Does this `ElementFilter` obviously exclude everything? If
|
||||
so, Beautiful Soup will issue a warning if you try to use it
|
||||
when parsing a document.
|
||||
|
||||
The `ElementFilter` might turn out to exclude everything even
|
||||
if this returns `False`, but it won't exclude everything in an
|
||||
obvious way.
|
||||
|
||||
The base `ElementFilter` implementation excludes things based
|
||||
on a match function we can't inspect, so excludes_everything
|
||||
is always false.
|
||||
"""
|
||||
return False
|
||||
|
||||
def match(self, element: PageElement, _known_rules:bool=False) -> bool:
|
||||
"""Does the given PageElement match the rules set down by this
|
||||
ElementFilter?
|
||||
|
||||
The base implementation delegates to the function passed in to
|
||||
the constructor.
|
||||
|
||||
:param _known_rules: Defined for compatibility with
|
||||
SoupStrainer._match(). Used more for consistency than because
|
||||
we need the performance optimization.
|
||||
"""
|
||||
if not _known_rules and self.includes_everything:
|
||||
return True
|
||||
if not self.match_function:
|
||||
return True
|
||||
return self.match_function(element)
|
||||
|
||||
def filter(self, generator: Iterator[PageElement]) -> Iterator[_OneElement]:
|
||||
"""The most generic search method offered by Beautiful Soup.
|
||||
|
||||
Acts like Python's built-in `filter`, using
|
||||
`ElementFilter.match` as the filtering function.
|
||||
"""
|
||||
# If there are no rules at all, don't bother filtering. Let
|
||||
# anything through.
|
||||
if self.includes_everything:
|
||||
yield from generator
|
||||
while True:
|
||||
try:
|
||||
i = next(generator)
|
||||
except StopIteration:
|
||||
break
|
||||
if i:
|
||||
if self.match(i, _known_rules=True):
|
||||
yield i
|
||||
|
||||
def find(self, generator: Iterator[PageElement]) -> _AtMostOneElement:
|
||||
"""A lower-level equivalent of :py:meth:`Tag.find`.
|
||||
|
||||
You can pass in your own generator for iterating over
|
||||
`PageElement` objects. The first one that matches this
|
||||
`ElementFilter` will be returned.
|
||||
|
||||
:param generator: A way of iterating over `PageElement`
|
||||
objects.
|
||||
"""
|
||||
for match in self.filter(generator):
|
||||
return match
|
||||
return None
|
||||
|
||||
def find_all(
|
||||
self, generator: Iterator[PageElement], limit: Optional[int] = None
|
||||
) -> _QueryResults:
|
||||
"""A lower-level equivalent of :py:meth:`Tag.find_all`.
|
||||
|
||||
You can pass in your own generator for iterating over
|
||||
`PageElement` objects. Only elements that match this
|
||||
`ElementFilter` will be returned in the :py:class:`ResultSet`.
|
||||
|
||||
:param generator: A way of iterating over `PageElement`
|
||||
objects.
|
||||
|
||||
:param limit: Stop looking after finding this many results.
|
||||
"""
|
||||
results = []
|
||||
for match in self.filter(generator):
|
||||
results.append(match)
|
||||
if limit is not None and len(results) >= limit:
|
||||
break
|
||||
return ResultSet(self, results)
|
||||
|
||||
def allow_tag_creation(
|
||||
self, nsprefix: Optional[str], name: str, attrs: Optional[_RawAttributeValues]
|
||||
) -> bool:
|
||||
"""Based on the name and attributes of a tag, see whether this
|
||||
`ElementFilter` will allow a `Tag` object to even be created.
|
||||
|
||||
By default, all tags are parsed. To change this, subclass
|
||||
`ElementFilter`.
|
||||
|
||||
:param name: The name of the prospective tag.
|
||||
:param attrs: The attributes of the prospective tag.
|
||||
"""
|
||||
return True
|
||||
|
||||
def allow_string_creation(self, string: str) -> bool:
|
||||
"""Based on the content of a string, see whether this
|
||||
`ElementFilter` will allow a `NavigableString` object based on
|
||||
this string to be added to the parse tree.
|
||||
|
||||
By default, all strings are processed into `NavigableString`
|
||||
objects. To change this, subclass `ElementFilter`.
|
||||
|
||||
:param str: The string under consideration.
|
||||
"""
|
||||
return True
|
||||
|
||||
|
||||
class MatchRule(object):
|
||||
"""Each MatchRule encapsulates the logic behind a single argument
|
||||
passed in to one of the Beautiful Soup find* methods.
|
||||
"""
|
||||
|
||||
string: Optional[str]
|
||||
pattern: Optional[_RegularExpressionProtocol]
|
||||
present: Optional[bool]
|
||||
exclude_everything: Optional[bool]
|
||||
# TODO-TYPING: All MatchRule objects also have an attribute
|
||||
# ``function``, but the type of the function depends on the
|
||||
# subclass.
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
string: Optional[Union[str, bytes]] = None,
|
||||
pattern: Optional[_RegularExpressionProtocol] = None,
|
||||
function: Optional[Callable] = None,
|
||||
present: Optional[bool] = None,
|
||||
exclude_everything: Optional[bool] = None
|
||||
):
|
||||
if isinstance(string, bytes):
|
||||
string = string.decode("utf8")
|
||||
self.string = string
|
||||
if isinstance(pattern, bytes):
|
||||
self.pattern = re.compile(pattern.decode("utf8"))
|
||||
elif isinstance(pattern, str):
|
||||
self.pattern = re.compile(pattern)
|
||||
else:
|
||||
self.pattern = pattern
|
||||
self.function = function
|
||||
self.present = present
|
||||
self.exclude_everything = exclude_everything
|
||||
|
||||
values = [
|
||||
x
|
||||
for x in (self.string, self.pattern, self.function, self.present, self.exclude_everything)
|
||||
if x is not None
|
||||
]
|
||||
if len(values) == 0:
|
||||
raise ValueError(
|
||||
"Either string, pattern, function, present, or exclude_everything must be provided."
|
||||
)
|
||||
if len(values) > 1:
|
||||
raise ValueError(
|
||||
"At most one of string, pattern, function, present, and exclude_everything must be provided."
|
||||
)
|
||||
|
||||
def _base_match(self, string: Optional[str]) -> Optional[bool]:
|
||||
"""Run the 'cheap' portion of a match, trying to get an answer without
|
||||
calling a potentially expensive custom function.
|
||||
|
||||
:return: True or False if we have a (positive or negative)
|
||||
match; None if we need to keep trying.
|
||||
"""
|
||||
# self.exclude_everything matches nothing.
|
||||
if self.exclude_everything:
|
||||
return False
|
||||
|
||||
# self.present==True matches everything except None.
|
||||
if self.present is True:
|
||||
return string is not None
|
||||
|
||||
# self.present==False matches _only_ None.
|
||||
if self.present is False:
|
||||
return string is None
|
||||
|
||||
# self.string does an exact string match.
|
||||
if self.string is not None:
|
||||
# print(f"{self.string} ?= {string}")
|
||||
return self.string == string
|
||||
|
||||
# self.pattern does a regular expression search.
|
||||
if self.pattern is not None:
|
||||
# print(f"{self.pattern} ?~ {string}")
|
||||
if string is None:
|
||||
return False
|
||||
return self.pattern.search(string) is not None
|
||||
|
||||
return None
|
||||
|
||||
def matches_string(self, string: Optional[str]) -> bool:
|
||||
_base_result = self._base_match(string)
|
||||
if _base_result is not None:
|
||||
# No need to invoke the test function.
|
||||
return _base_result
|
||||
if self.function is not None and not self.function(string):
|
||||
# print(f"{self.function}({string}) == False")
|
||||
return False
|
||||
return True
|
||||
|
||||
def __repr__(self) -> str:
|
||||
cls = type(self).__name__
|
||||
return f"<{cls} string={self.string} pattern={self.pattern} function={self.function} present={self.present}>"
|
||||
|
||||
def __eq__(self, other: Any) -> bool:
|
||||
return (
|
||||
isinstance(other, MatchRule)
|
||||
and self.string == other.string
|
||||
and self.pattern == other.pattern
|
||||
and self.function == other.function
|
||||
and self.present == other.present
|
||||
)
|
||||
|
||||
|
||||
class TagNameMatchRule(MatchRule):
|
||||
"""A MatchRule implementing the rules for matches against tag name."""
|
||||
|
||||
function: Optional[_TagMatchFunction]
|
||||
|
||||
def matches_tag(self, tag: Tag) -> bool:
|
||||
base_value = self._base_match(tag.name)
|
||||
if base_value is not None:
|
||||
return base_value
|
||||
|
||||
# The only remaining possibility is that the match is determined
|
||||
# by a function call. Call the function.
|
||||
function = cast(_TagMatchFunction, self.function)
|
||||
if function(tag):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
class AttributeValueMatchRule(MatchRule):
|
||||
"""A MatchRule implementing the rules for matches against attribute value."""
|
||||
|
||||
function: Optional[_NullableStringMatchFunction]
|
||||
|
||||
|
||||
class StringMatchRule(MatchRule):
|
||||
"""A MatchRule implementing the rules for matches against a NavigableString."""
|
||||
|
||||
function: Optional[_StringMatchFunction]
|
||||
|
||||
|
||||
class SoupStrainer(ElementFilter):
|
||||
"""The `ElementFilter` subclass used internally by Beautiful Soup.
|
||||
|
||||
A `SoupStrainer` encapsulates the logic necessary to perform the
|
||||
kind of matches supported by methods such as
|
||||
:py:meth:`Tag.find`. `SoupStrainer` objects are primarily created
|
||||
internally, but you can create one yourself and pass it in as
|
||||
``parse_only`` to the `BeautifulSoup` constructor, to parse a
|
||||
subset of a large document.
|
||||
|
||||
Internally, `SoupStrainer` objects work by converting the
|
||||
constructor arguments into `MatchRule` objects. Incoming
|
||||
tags/markup are matched against those rules.
|
||||
|
||||
:param name: One or more restrictions on the tags found in a document.
|
||||
|
||||
:param attrs: A dictionary that maps attribute names to
|
||||
restrictions on tags that use those attributes.
|
||||
|
||||
:param string: One or more restrictions on the strings found in a
|
||||
document.
|
||||
|
||||
:param kwargs: A dictionary that maps attribute names to restrictions
|
||||
on tags that use those attributes. These restrictions are additive to
|
||||
any specified in ``attrs``.
|
||||
|
||||
"""
|
||||
|
||||
name_rules: List[TagNameMatchRule]
|
||||
attribute_rules: Dict[str, List[AttributeValueMatchRule]]
|
||||
string_rules: List[StringMatchRule]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: Optional[_StrainableElement] = None,
|
||||
attrs: Optional[Dict[str, _StrainableAttribute]] = None,
|
||||
string: Optional[_StrainableString] = None,
|
||||
**kwargs: _StrainableAttribute,
|
||||
):
|
||||
if string is None and "text" in kwargs:
|
||||
string = cast(Optional[_StrainableString], kwargs.pop("text"))
|
||||
warnings.warn(
|
||||
"As of version 4.11.0, the 'text' argument to the SoupStrainer constructor is deprecated. Use 'string' instead.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
|
||||
if name is None and not attrs and not string and not kwargs:
|
||||
# Special case for backwards compatibility. Instantiating
|
||||
# a SoupStrainer with no arguments whatsoever gets you one
|
||||
# that matches all Tags, and only Tags.
|
||||
self.name_rules = [TagNameMatchRule(present=True)]
|
||||
else:
|
||||
self.name_rules = cast(
|
||||
List[TagNameMatchRule], list(self._make_match_rules(name, TagNameMatchRule))
|
||||
)
|
||||
self.attribute_rules = defaultdict(list)
|
||||
|
||||
if attrs is None:
|
||||
attrs = {}
|
||||
if not isinstance(attrs, dict):
|
||||
# Passing something other than a dictionary as attrs is
|
||||
# sugar for matching that thing against the 'class'
|
||||
# attribute.
|
||||
attrs = {"class": attrs}
|
||||
|
||||
for attrdict in attrs, kwargs:
|
||||
for attr, value in attrdict.items():
|
||||
if attr == "class_" and attrdict is kwargs:
|
||||
# If you pass in 'class_' as part of kwargs, it's
|
||||
# because class is a Python reserved word. If you
|
||||
# pass it in as part of the attrs dict, it's
|
||||
# because you really are looking for an attribute
|
||||
# called 'class_'.
|
||||
attr = "class"
|
||||
|
||||
if value is None:
|
||||
value = False
|
||||
for rule_obj in self._make_match_rules(value, AttributeValueMatchRule):
|
||||
self.attribute_rules[attr].append(
|
||||
cast(AttributeValueMatchRule, rule_obj)
|
||||
)
|
||||
|
||||
self.string_rules = cast(
|
||||
List[StringMatchRule], list(self._make_match_rules(string, StringMatchRule))
|
||||
)
|
||||
|
||||
#: DEPRECATED 4.13.0: You shouldn't need to check this under
|
||||
#: any name (.string or .text), and if you do, you're probably
|
||||
#: not taking into account all of the types of values this
|
||||
#: variable might have. Look at the .string_rules list instead.
|
||||
self.__string = string
|
||||
|
||||
@property
|
||||
def includes_everything(self) -> bool:
|
||||
"""Check whether the provided rules will obviously include
|
||||
everything. (They might include everything even if this returns `False`,
|
||||
but not in an obvious way.)
|
||||
"""
|
||||
return not self.name_rules and not self.string_rules and not self.attribute_rules
|
||||
|
||||
@property
|
||||
def excludes_everything(self) -> bool:
|
||||
"""Check whether the provided rules will obviously exclude
|
||||
everything. (They might exclude everything even if this returns `False`,
|
||||
but not in an obvious way.)
|
||||
"""
|
||||
if (self.string_rules and (self.name_rules or self.attribute_rules)):
|
||||
# This is self-contradictory, so the rules exclude everything.
|
||||
return True
|
||||
|
||||
# If there's a rule that ended up treated as an "exclude everything"
|
||||
# rule due to creating a logical inconsistency, then the rules
|
||||
# exclude everything.
|
||||
if any(x.exclude_everything for x in self.string_rules):
|
||||
return True
|
||||
if any(x.exclude_everything for x in self.name_rules):
|
||||
return True
|
||||
for ruleset in self.attribute_rules.values():
|
||||
if any(x.exclude_everything for x in ruleset):
|
||||
return True
|
||||
return False
|
||||
|
||||
@property
|
||||
def string(self) -> Optional[_StrainableString]:
|
||||
":meta private:"
|
||||
warnings.warn(
|
||||
"Access to deprecated property string. (Look at .string_rules instead) -- Deprecated since version 4.13.0.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
return self.__string
|
||||
|
||||
@property
|
||||
def text(self) -> Optional[_StrainableString]:
|
||||
":meta private:"
|
||||
warnings.warn(
|
||||
"Access to deprecated property text. (Look at .string_rules instead) -- Deprecated since version 4.13.0.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
return self.__string
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<{self.__class__.__name__} name={self.name_rules} attrs={self.attribute_rules} string={self.string_rules}>"
|
||||
|
||||
@classmethod
|
||||
def _make_match_rules(
|
||||
cls,
|
||||
obj: Optional[Union[_StrainableElement, _StrainableAttribute]],
|
||||
rule_class: Type[MatchRule],
|
||||
) -> Iterator[MatchRule]:
|
||||
"""Convert a vaguely-specific 'object' into one or more well-defined
|
||||
`MatchRule` objects.
|
||||
|
||||
:param obj: Some kind of object that corresponds to one or more
|
||||
matching rules.
|
||||
:param rule_class: Create instances of this `MatchRule` subclass.
|
||||
"""
|
||||
if obj is None:
|
||||
return
|
||||
if isinstance(obj, (str, bytes)):
|
||||
yield rule_class(string=obj)
|
||||
elif isinstance(obj, bool):
|
||||
yield rule_class(present=obj)
|
||||
elif callable(obj):
|
||||
yield rule_class(function=obj)
|
||||
elif isinstance(obj, _RegularExpressionProtocol):
|
||||
yield rule_class(pattern=obj)
|
||||
elif hasattr(obj, "__iter__"):
|
||||
if not obj:
|
||||
# The attribute is being matched against the null set,
|
||||
# which means it should exclude everything.
|
||||
yield rule_class(exclude_everything=True)
|
||||
for o in obj:
|
||||
if not isinstance(o, (bytes, str)) and hasattr(o, "__iter__"):
|
||||
# This is almost certainly the user's
|
||||
# mistake. This list contains another list, which
|
||||
# opens up the possibility of infinite
|
||||
# self-reference. In the interests of avoiding
|
||||
# infinite recursion, we'll treat this as an
|
||||
# impossible match and issue a rule that excludes
|
||||
# everything, rather than looking inside.
|
||||
warnings.warn(
|
||||
f"Ignoring nested list {o} to avoid the possibility of infinite recursion.",
|
||||
stacklevel=5,
|
||||
)
|
||||
yield rule_class(exclude_everything=True)
|
||||
continue
|
||||
for x in cls._make_match_rules(o, rule_class):
|
||||
yield x
|
||||
else:
|
||||
yield rule_class(string=str(obj))
|
||||
|
||||
def matches_tag(self, tag: Tag) -> bool:
|
||||
"""Do the rules of this `SoupStrainer` trigger a match against the
|
||||
given `Tag`?
|
||||
|
||||
If the `SoupStrainer` has any `TagNameMatchRule`, at least one
|
||||
must match the `Tag` or its `Tag.name`.
|
||||
|
||||
If there are any `AttributeValueMatchRule` for a given
|
||||
attribute, at least one of them must match the attribute
|
||||
value.
|
||||
|
||||
If there are any `StringMatchRule`, at least one must match,
|
||||
but a `SoupStrainer` that *only* contains `StringMatchRule`
|
||||
cannot match a `Tag`, only a `NavigableString`.
|
||||
"""
|
||||
# If there are no rules at all, let anything through.
|
||||
#if self.includes_everything:
|
||||
# return True
|
||||
|
||||
# String rules cannot not match a Tag on their own.
|
||||
if not self.name_rules and not self.attribute_rules:
|
||||
return False
|
||||
|
||||
# Optimization for a very common case where the user is
|
||||
# searching for a tag with one specific name, and we're
|
||||
# looking at a tag with a different name.
|
||||
if (
|
||||
not tag.prefix
|
||||
and len(self.name_rules) == 1
|
||||
and self.name_rules[0].string is not None
|
||||
and tag.name != self.name_rules[0].string
|
||||
):
|
||||
return False
|
||||
|
||||
# If there are name rules, at least one must match. It can
|
||||
# match either the Tag object itself or the prefixed name of
|
||||
# the tag.
|
||||
prefixed_name = None
|
||||
if tag.prefix:
|
||||
prefixed_name = f"{tag.prefix}:{tag.name}"
|
||||
if self.name_rules:
|
||||
name_matches = False
|
||||
for rule in self.name_rules:
|
||||
# attrs = " ".join(
|
||||
# [f"{k}={v}" for k, v in sorted(tag.attrs.items())]
|
||||
# )
|
||||
# print(f"Testing <{tag.name} {attrs}>{tag.string}</{tag.name}> against {rule}")
|
||||
|
||||
# If the rule contains a function, the function will be called
|
||||
# with `tag`. It will not be called a second time with
|
||||
# `prefixed_name`.
|
||||
if rule.matches_tag(tag) or (
|
||||
not rule.function and prefixed_name is not None and rule.matches_string(prefixed_name)
|
||||
):
|
||||
name_matches = True
|
||||
break
|
||||
|
||||
if not name_matches:
|
||||
return False
|
||||
|
||||
# If there are attribute rules for a given attribute, at least
|
||||
# one of them must match. If there are rules for multiple
|
||||
# attributes, each attribute must have at least one match.
|
||||
for attr, rules in self.attribute_rules.items():
|
||||
attr_value = tag.get(attr, None)
|
||||
this_attr_match = self._attribute_match(attr_value, rules)
|
||||
if not this_attr_match:
|
||||
return False
|
||||
|
||||
# If there are string rules, at least one must match.
|
||||
if self.string_rules:
|
||||
_str = tag.string
|
||||
if _str is None:
|
||||
return False
|
||||
if not self.matches_any_string_rule(_str):
|
||||
return False
|
||||
return True
|
||||
|
||||
def _attribute_match(
|
||||
self,
|
||||
attr_value: Optional[_AttributeValue],
|
||||
rules: Iterable[AttributeValueMatchRule],
|
||||
) -> bool:
|
||||
attr_values: Sequence[Optional[str]]
|
||||
if isinstance(attr_value, list):
|
||||
attr_values = attr_value
|
||||
else:
|
||||
attr_values = [cast(str, attr_value)]
|
||||
|
||||
def _match_attribute_value_helper(attr_values: Sequence[Optional[str]]) -> bool:
|
||||
for rule in rules:
|
||||
for attr_value in attr_values:
|
||||
if rule.matches_string(attr_value):
|
||||
return True
|
||||
return False
|
||||
|
||||
this_attr_match = _match_attribute_value_helper(attr_values)
|
||||
if not this_attr_match and len(attr_values) != 1:
|
||||
# Try again but treat the attribute value as a single
|
||||
# string instead of a list. The result can only be
|
||||
# different if the list of values contains more or less
|
||||
# than one item.
|
||||
|
||||
# This cast converts Optional[str] to plain str.
|
||||
#
|
||||
# We know there can't be any None in the list. Beautiful
|
||||
# Soup never uses None as a value of a multi-valued
|
||||
# attribute, and if None is passed in as attr_value, it's
|
||||
# turned into a list with 1 element, which was excluded by
|
||||
# the if statement above.
|
||||
attr_values = cast(Sequence[str], attr_values)
|
||||
|
||||
joined_attr_value = " ".join(attr_values)
|
||||
this_attr_match = _match_attribute_value_helper([joined_attr_value])
|
||||
return this_attr_match
|
||||
|
||||
def allow_tag_creation(
|
||||
self, nsprefix: Optional[str], name: str, attrs: Optional[_RawAttributeValues]
|
||||
) -> bool:
|
||||
"""Based on the name and attributes of a tag, see whether this
|
||||
`SoupStrainer` will allow a `Tag` object to even be created.
|
||||
|
||||
:param name: The name of the prospective tag.
|
||||
:param attrs: The attributes of the prospective tag.
|
||||
"""
|
||||
if self.string_rules:
|
||||
# A SoupStrainer that has string rules can't be used to
|
||||
# manage tag creation, because the string rule can't be
|
||||
# evaluated until after the tag and all of its contents
|
||||
# have been parsed.
|
||||
return False
|
||||
prefixed_name = None
|
||||
if nsprefix:
|
||||
prefixed_name = f"{nsprefix}:{name}"
|
||||
if self.name_rules:
|
||||
# At least one name rule must match.
|
||||
name_match = False
|
||||
for rule in self.name_rules:
|
||||
for x in name, prefixed_name:
|
||||
if x is not None:
|
||||
if rule.matches_string(x):
|
||||
name_match = True
|
||||
break
|
||||
if not name_match:
|
||||
return False
|
||||
|
||||
# For each attribute that has rules, at least one rule must
|
||||
# match.
|
||||
if attrs is None:
|
||||
attrs = AttributeDict()
|
||||
for attr, rules in self.attribute_rules.items():
|
||||
attr_value = attrs.get(attr)
|
||||
if not self._attribute_match(attr_value, rules):
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def allow_string_creation(self, string: str) -> bool:
|
||||
"""Based on the content of a markup string, see whether this
|
||||
`SoupStrainer` will allow it to be instantiated as a
|
||||
`NavigableString` object, or whether it should be ignored.
|
||||
"""
|
||||
if self.name_rules or self.attribute_rules:
|
||||
# A SoupStrainer that has name or attribute rules won't
|
||||
# match any strings; it's designed to match tags with
|
||||
# certain properties.
|
||||
return False
|
||||
if not self.string_rules:
|
||||
# A SoupStrainer with no string rules will match
|
||||
# all strings.
|
||||
return True
|
||||
if not self.matches_any_string_rule(string):
|
||||
return False
|
||||
return True
|
||||
|
||||
def matches_any_string_rule(self, string: str) -> bool:
|
||||
"""See whether the content of a string matches any of
|
||||
this `SoupStrainer`'s string rules.
|
||||
"""
|
||||
if not self.string_rules:
|
||||
return True
|
||||
for string_rule in self.string_rules:
|
||||
if string_rule.matches_string(string):
|
||||
return True
|
||||
return False
|
||||
|
||||
def match(self, element: PageElement, _known_rules: bool=False) -> bool:
|
||||
"""Does the given `PageElement` match the rules set down by this
|
||||
`SoupStrainer`?
|
||||
|
||||
The find_* methods rely heavily on this method to find matches.
|
||||
|
||||
:param element: A `PageElement`.
|
||||
:param _known_rules: Set to true in the common case where
|
||||
we already checked and found at least one rule in this SoupStrainer
|
||||
that might exclude a PageElement. Without this, we need
|
||||
to check .includes_everything every time, just to be safe.
|
||||
:return: `True` if the element matches this `SoupStrainer`'s rules; `False` otherwise.
|
||||
"""
|
||||
# If there are no rules at all, let anything through.
|
||||
if not _known_rules and self.includes_everything:
|
||||
return True
|
||||
if isinstance(element, Tag):
|
||||
return self.matches_tag(element)
|
||||
assert isinstance(element, NavigableString)
|
||||
if not (self.name_rules or self.attribute_rules):
|
||||
# A NavigableString can only match a SoupStrainer that
|
||||
# does not define any name or attribute rules.
|
||||
# Then it comes down to the string rules.
|
||||
return self.matches_any_string_rule(element)
|
||||
return False
|
||||
|
||||
@_deprecated("allow_tag_creation", "4.13.0")
|
||||
def search_tag(self, name: str, attrs: Optional[_RawAttributeValues]) -> bool:
|
||||
"""A less elegant version of `allow_tag_creation`. Deprecated as of 4.13.0"""
|
||||
":meta private:"
|
||||
return self.allow_tag_creation(None, name, attrs)
|
||||
|
||||
@_deprecated("match", "4.13.0")
|
||||
def search(self, element: PageElement) -> Optional[PageElement]:
|
||||
"""A less elegant version of match(). Deprecated as of 4.13.0.
|
||||
|
||||
:meta private:
|
||||
"""
|
||||
return element if self.match(element) else None
|
||||
+276
@@ -0,0 +1,276 @@
|
||||
from __future__ import annotations
|
||||
from typing import Callable, Dict, Iterable, Optional, Set, Tuple, TYPE_CHECKING, Union
|
||||
from typing_extensions import TypeAlias
|
||||
from bs4.dammit import EntitySubstitution
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from bs4._typing import _AttributeValue
|
||||
|
||||
|
||||
class Formatter(EntitySubstitution):
|
||||
"""Describes a strategy to use when outputting a parse tree to a string.
|
||||
|
||||
Some parts of this strategy come from the distinction between
|
||||
HTML4, HTML5, and XML. Others are configurable by the user.
|
||||
|
||||
Formatters are passed in as the `formatter` argument to methods
|
||||
like `bs4.element.Tag.encode`. Most people won't need to
|
||||
think about formatters, and most people who need to think about
|
||||
them can pass in one of these predefined strings as `formatter`
|
||||
rather than making a new Formatter object:
|
||||
|
||||
For HTML documents:
|
||||
* 'html' - HTML entity substitution for generic HTML documents. (default)
|
||||
* 'html5' - HTML entity substitution for HTML5 documents, as
|
||||
well as some optimizations in the way tags are rendered.
|
||||
* 'html5-4.12.0' - The version of the 'html5' formatter used prior to
|
||||
Beautiful Soup 4.13.0.
|
||||
* 'minimal' - Only make the substitutions necessary to guarantee
|
||||
valid HTML.
|
||||
* None - Do not perform any substitution. This will be faster
|
||||
but may result in invalid markup.
|
||||
|
||||
For XML documents:
|
||||
* 'html' - Entity substitution for XHTML documents.
|
||||
* 'minimal' - Only make the substitutions necessary to guarantee
|
||||
valid XML. (default)
|
||||
* None - Do not perform any substitution. This will be faster
|
||||
but may result in invalid markup.
|
||||
|
||||
"""
|
||||
|
||||
#: Constant name denoting HTML markup
|
||||
HTML: str = "html"
|
||||
|
||||
#: Constant name denoting XML markup
|
||||
XML: str = "xml"
|
||||
|
||||
#: Default values for the various constructor options when the
|
||||
#: markup language is HTML.
|
||||
HTML_DEFAULTS: Dict[str, Set[str]] = dict(
|
||||
cdata_containing_tags=set(["script", "style"]),
|
||||
)
|
||||
|
||||
language: Optional[str] #: :meta private:
|
||||
entity_substitution: Optional[_EntitySubstitutionFunction] #: :meta private:
|
||||
void_element_close_prefix: str #: :meta private:
|
||||
cdata_containing_tags: Set[str] #: :meta private:
|
||||
indent: str #: :meta private:
|
||||
|
||||
#: If this is set to true by the constructor, then attributes whose
|
||||
#: values are sent to the empty string will be treated as HTML
|
||||
#: boolean attributes. (Attributes whose value is None are always
|
||||
#: rendered this way.)
|
||||
empty_attributes_are_booleans: bool
|
||||
|
||||
def _default(
|
||||
self, language: str, value: Optional[Set[str]], kwarg: str
|
||||
) -> Set[str]:
|
||||
if value is not None:
|
||||
return value
|
||||
if language == self.XML:
|
||||
# When XML is the markup language in use, all of the
|
||||
# defaults are the empty list.
|
||||
return set()
|
||||
|
||||
# Otherwise, it depends on what's in HTML_DEFAULTS.
|
||||
return self.HTML_DEFAULTS[kwarg]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
language: Optional[str] = None,
|
||||
entity_substitution: Optional[_EntitySubstitutionFunction] = None,
|
||||
void_element_close_prefix: str = "/",
|
||||
cdata_containing_tags: Optional[Set[str]] = None,
|
||||
empty_attributes_are_booleans: bool = False,
|
||||
indent: Union[int,str] = 1,
|
||||
):
|
||||
r"""Constructor.
|
||||
|
||||
:param language: This should be `Formatter.XML` if you are formatting
|
||||
XML markup and `Formatter.HTML` if you are formatting HTML markup.
|
||||
|
||||
:param entity_substitution: A function to call to replace special
|
||||
characters with XML/HTML entities. For examples, see
|
||||
bs4.dammit.EntitySubstitution.substitute_html and substitute_xml.
|
||||
:param void_element_close_prefix: By default, void elements
|
||||
are represented as <tag/> (XML rules) rather than <tag>
|
||||
(HTML rules). To get <tag>, pass in the empty string.
|
||||
:param cdata_containing_tags: The set of tags that are defined
|
||||
as containing CDATA in this dialect. For example, in HTML,
|
||||
<script> and <style> tags are defined as containing CDATA,
|
||||
and their contents should not be formatted.
|
||||
:param empty_attributes_are_booleans: If this is set to true,
|
||||
then attributes whose values are sent to the empty string
|
||||
will be treated as `HTML boolean
|
||||
attributes<https://dev.w3.org/html5/spec-LC/common-microsyntaxes.html#boolean-attributes>`_. (Attributes
|
||||
whose value is None are always rendered this way.)
|
||||
:param indent: If indent is a non-negative integer or string,
|
||||
then the contents of elements will be indented
|
||||
appropriately when pretty-printing. An indent level of 0,
|
||||
negative, or "" will only insert newlines. Using a
|
||||
positive integer indent indents that many spaces per
|
||||
level. If indent is a string (such as "\t"), that string
|
||||
is used to indent each level. The default behavior is to
|
||||
indent one space per level.
|
||||
|
||||
"""
|
||||
self.language = language or self.HTML
|
||||
self.entity_substitution = entity_substitution
|
||||
self.void_element_close_prefix = void_element_close_prefix
|
||||
self.cdata_containing_tags = self._default(
|
||||
self.language, cdata_containing_tags, "cdata_containing_tags"
|
||||
)
|
||||
self.empty_attributes_are_booleans = empty_attributes_are_booleans
|
||||
if indent is None:
|
||||
indent = 0
|
||||
indent_str: str
|
||||
if isinstance(indent, int):
|
||||
if indent < 0:
|
||||
indent = 0
|
||||
indent_str = " " * indent
|
||||
elif isinstance(indent, str):
|
||||
indent_str = indent
|
||||
else:
|
||||
indent_str = " "
|
||||
self.indent = indent_str
|
||||
|
||||
def substitute(self, ns: str) -> str:
|
||||
"""Process a string that needs to undergo entity substitution.
|
||||
This may be a string encountered in an attribute value or as
|
||||
text.
|
||||
|
||||
:param ns: A string.
|
||||
:return: The same string but with certain characters replaced by named
|
||||
or numeric entities.
|
||||
"""
|
||||
if not self.entity_substitution:
|
||||
return ns
|
||||
from .element import NavigableString
|
||||
|
||||
if (
|
||||
isinstance(ns, NavigableString)
|
||||
and ns.parent is not None
|
||||
and ns.parent.name in self.cdata_containing_tags
|
||||
):
|
||||
# Do nothing.
|
||||
return ns
|
||||
# Substitute.
|
||||
return self.entity_substitution(ns)
|
||||
|
||||
def attribute_value(self, value: str) -> str:
|
||||
"""Process the value of an attribute.
|
||||
|
||||
:param ns: A string.
|
||||
:return: A string with certain characters replaced by named
|
||||
or numeric entities.
|
||||
"""
|
||||
return self.substitute(value)
|
||||
|
||||
def attributes(
|
||||
self, tag: bs4.element.Tag # type:ignore
|
||||
) -> Iterable[Tuple[str, Optional[_AttributeValue]]]:
|
||||
"""Reorder a tag's attributes however you want.
|
||||
|
||||
By default, attributes are sorted alphabetically. This makes
|
||||
behavior consistent between Python 2 and Python 3, and preserves
|
||||
backwards compatibility with older versions of Beautiful Soup.
|
||||
|
||||
If `empty_attributes_are_booleans` is True, then
|
||||
attributes whose values are set to the empty string will be
|
||||
treated as boolean attributes.
|
||||
"""
|
||||
if tag.attrs is None:
|
||||
return []
|
||||
|
||||
items: Iterable[Tuple[str, _AttributeValue]] = list(tag.attrs.items())
|
||||
return sorted(
|
||||
(k, (None if self.empty_attributes_are_booleans and v == "" else v))
|
||||
for k, v in items
|
||||
)
|
||||
|
||||
|
||||
class HTMLFormatter(Formatter):
|
||||
"""A generic Formatter for HTML."""
|
||||
|
||||
REGISTRY: Dict[Optional[str], HTMLFormatter] = {}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
entity_substitution: Optional[_EntitySubstitutionFunction] = None,
|
||||
void_element_close_prefix: str = "/",
|
||||
cdata_containing_tags: Optional[Set[str]] = None,
|
||||
empty_attributes_are_booleans: bool = False,
|
||||
indent: Union[int,str] = 1,
|
||||
):
|
||||
super(HTMLFormatter, self).__init__(
|
||||
self.HTML,
|
||||
entity_substitution,
|
||||
void_element_close_prefix,
|
||||
cdata_containing_tags,
|
||||
empty_attributes_are_booleans,
|
||||
indent=indent
|
||||
)
|
||||
|
||||
|
||||
class XMLFormatter(Formatter):
|
||||
"""A generic Formatter for XML."""
|
||||
|
||||
REGISTRY: Dict[Optional[str], XMLFormatter] = {}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
entity_substitution: Optional[_EntitySubstitutionFunction] = None,
|
||||
void_element_close_prefix: str = "/",
|
||||
cdata_containing_tags: Optional[Set[str]] = None,
|
||||
empty_attributes_are_booleans: bool = False,
|
||||
indent: Union[int,str] = 1,
|
||||
):
|
||||
super(XMLFormatter, self).__init__(
|
||||
self.XML,
|
||||
entity_substitution,
|
||||
void_element_close_prefix,
|
||||
cdata_containing_tags,
|
||||
empty_attributes_are_booleans,
|
||||
indent=indent,
|
||||
)
|
||||
|
||||
|
||||
# Set up aliases for the default formatters.
|
||||
HTMLFormatter.REGISTRY["html"] = HTMLFormatter(
|
||||
entity_substitution=EntitySubstitution.substitute_html
|
||||
)
|
||||
|
||||
HTMLFormatter.REGISTRY["html5"] = HTMLFormatter(
|
||||
entity_substitution=EntitySubstitution.substitute_html5,
|
||||
void_element_close_prefix="",
|
||||
empty_attributes_are_booleans=True,
|
||||
)
|
||||
HTMLFormatter.REGISTRY["html5-4.12"] = HTMLFormatter(
|
||||
entity_substitution=EntitySubstitution.substitute_html,
|
||||
void_element_close_prefix="",
|
||||
empty_attributes_are_booleans=True,
|
||||
)
|
||||
HTMLFormatter.REGISTRY["minimal"] = HTMLFormatter(
|
||||
entity_substitution=EntitySubstitution.substitute_xml
|
||||
)
|
||||
HTMLFormatter.REGISTRY[None] = HTMLFormatter(entity_substitution=None)
|
||||
XMLFormatter.REGISTRY["html"] = XMLFormatter(
|
||||
entity_substitution=EntitySubstitution.substitute_html
|
||||
)
|
||||
XMLFormatter.REGISTRY["minimal"] = XMLFormatter(
|
||||
entity_substitution=EntitySubstitution.substitute_xml
|
||||
)
|
||||
|
||||
XMLFormatter.REGISTRY[None] = XMLFormatter(entity_substitution=None)
|
||||
|
||||
# Define type aliases to improve readability.
|
||||
#
|
||||
|
||||
#: A function to call to replace special characters with XML or HTML
|
||||
#: entities.
|
||||
_EntitySubstitutionFunction: TypeAlias = Callable[[str], str]
|
||||
|
||||
# Many of the output-centered methods take an argument that can either
|
||||
# be a Formatter object or the name of a Formatter to be looked up.
|
||||
_FormatterOrName = Union[Formatter, str]
|
||||
Whitespace-only changes.
+221
@@ -0,0 +1,221 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"packages": [
|
||||
{
|
||||
"distribution": "beautifulsoup4",
|
||||
"version": "4.15.0",
|
||||
"modules": [
|
||||
"bs4"
|
||||
],
|
||||
"licenses": [
|
||||
"beautifulsoup4-4.15.0.dist-info/licenses/AUTHORS",
|
||||
"beautifulsoup4-4.15.0.dist-info/licenses/LICENSE"
|
||||
],
|
||||
"origin": "Exact pure Python runtime source from the existing pinned recovery environment; no platform binary copied"
|
||||
},
|
||||
{
|
||||
"distribution": "soupsieve",
|
||||
"version": "3.0.4",
|
||||
"modules": [
|
||||
"soupsieve"
|
||||
],
|
||||
"licenses": [
|
||||
"soupsieve-3.0.4.dist-info/licenses/LICENSE.md"
|
||||
],
|
||||
"origin": "Exact pure Python runtime source from the existing pinned recovery environment; no platform binary copied"
|
||||
},
|
||||
{
|
||||
"distribution": "typing_extensions",
|
||||
"version": "4.16.0",
|
||||
"modules": [
|
||||
"typing_extensions.py"
|
||||
],
|
||||
"licenses": [
|
||||
"typing_extensions-4.16.0.dist-info/licenses/LICENSE"
|
||||
],
|
||||
"origin": "Exact pure Python runtime source from the existing pinned recovery environment; no platform binary copied"
|
||||
}
|
||||
],
|
||||
"files": [
|
||||
{
|
||||
"path": "README.md",
|
||||
"bytes": 758,
|
||||
"sha256": "af6f426e4a93bddad27a441df61b5e122aa45d7273c12fb9199981e0ef716a52"
|
||||
},
|
||||
{
|
||||
"path": "beautifulsoup4-4.15.0.dist-info/METADATA",
|
||||
"bytes": 3812,
|
||||
"sha256": "b2f888103259f1607c85f3b1163be1bc49fc9941a3243c3b89a21075bfc6d4fb"
|
||||
},
|
||||
{
|
||||
"path": "beautifulsoup4-4.15.0.dist-info/WHEEL",
|
||||
"bytes": 87,
|
||||
"sha256": "aad0b0a12256807936d52d4a6f88a1773236ae527564a688bab4e3fe780e8724"
|
||||
},
|
||||
{
|
||||
"path": "beautifulsoup4-4.15.0.dist-info/licenses/AUTHORS",
|
||||
"bytes": 2201,
|
||||
"sha256": "b989238918e1fdac1e46717cb405b63e92497a272413af0d989c1df6c8abcb6f"
|
||||
},
|
||||
{
|
||||
"path": "beautifulsoup4-4.15.0.dist-info/licenses/LICENSE",
|
||||
"bytes": 1441,
|
||||
"sha256": "55b4d8d4b1e5bc86d10efac91b74c87bcb77526b0f5b9edaf8b9cd2adc7397b2"
|
||||
},
|
||||
{
|
||||
"path": "bs4/__init__.py",
|
||||
"bytes": 44562,
|
||||
"sha256": "90e007f82a9fc5bcf22a8df3b395b7bc5245e54d65cd68fd51ca12a414718d4e"
|
||||
},
|
||||
{
|
||||
"path": "bs4/_deprecation.py",
|
||||
"bytes": 2408,
|
||||
"sha256": "9e21c90a4dfb00f83c284b8539ae7b6576b12dd06673fd95eaeb9a26abbbaf7d"
|
||||
},
|
||||
{
|
||||
"path": "bs4/_typing.py",
|
||||
"bytes": 7549,
|
||||
"sha256": "ccd731ed1d720932bc5b0b6e98fdbc85cec2277a4cc995e3fd501e61a3573190"
|
||||
},
|
||||
{
|
||||
"path": "bs4/_warnings.py",
|
||||
"bytes": 4711,
|
||||
"sha256": "66e3844e072711b660c363749e73579fac2fb6b9f6badec017477df1bbe43057"
|
||||
},
|
||||
{
|
||||
"path": "bs4/builder/__init__.py",
|
||||
"bytes": 31194,
|
||||
"sha256": "465e2a8ce5ef772cb28dac8e16a6e4828528a3cd48828c8a0fe47059e54ae7d8"
|
||||
},
|
||||
{
|
||||
"path": "bs4/builder/_html5lib.py",
|
||||
"bytes": 23607,
|
||||
"sha256": "84beb1524e3f2368b908c82e16860596b236e9c6380eeb7b7ce110ad472d1c83"
|
||||
},
|
||||
{
|
||||
"path": "bs4/builder/_htmlparser.py",
|
||||
"bytes": 19866,
|
||||
"sha256": "4ab8d0bee2fc48a3ab5f28f33611355d3049a46b25a44d4b2bedc1d6f9bbfebd"
|
||||
},
|
||||
{
|
||||
"path": "bs4/builder/_lxml.py",
|
||||
"bytes": 18969,
|
||||
"sha256": "92cd5ef1ba00fe7380da8a26021c5eb9d71c47a4e16c413e125945a874683cb0"
|
||||
},
|
||||
{
|
||||
"path": "bs4/css.py",
|
||||
"bytes": 12713,
|
||||
"sha256": "fe6fe5ff84865879d8eb6d15276d63fea407d515f7a7dd6c6157a680ac5a2ec3"
|
||||
},
|
||||
{
|
||||
"path": "bs4/dammit.py",
|
||||
"bytes": 57485,
|
||||
"sha256": "d261705bff87925c9ba2dfcc8378284ea6187ca7e5b8a253fd6254e288db405e"
|
||||
},
|
||||
{
|
||||
"path": "bs4/diagnose.py",
|
||||
"bytes": 7846,
|
||||
"sha256": "6adf7c8aec723aba9e73857c8b091321b354a810acabd2ebddf0c0431db5dbd6"
|
||||
},
|
||||
{
|
||||
"path": "bs4/element.py",
|
||||
"bytes": 125805,
|
||||
"sha256": "a109bc64af4fd5137b4e739ac254b9c1d518c2cb36391d21e59113e95b862641"
|
||||
},
|
||||
{
|
||||
"path": "bs4/exceptions.py",
|
||||
"bytes": 951,
|
||||
"sha256": "43d14e69d35ef1046fcc331a2925ded96b65f092bfa00656ee66c564154ffc61"
|
||||
},
|
||||
{
|
||||
"path": "bs4/filter.py",
|
||||
"bytes": 29180,
|
||||
"sha256": "77dc2d587920f1cc776d4d013e32de1a01691d5391cd7e870277ed07aaec5ea3"
|
||||
},
|
||||
{
|
||||
"path": "bs4/formatter.py",
|
||||
"bytes": 10478,
|
||||
"sha256": "b814f493a5bc3b9909f4f0ae2588eb6bdef2a14a82f9d94cf43feffa844cd2bf"
|
||||
},
|
||||
{
|
||||
"path": "bs4/py.typed",
|
||||
"bytes": 0,
|
||||
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
||||
},
|
||||
{
|
||||
"path": "soupsieve/__init__.py",
|
||||
"bytes": 6397,
|
||||
"sha256": "62769d4e6151f5c6ffcbc5a3f9890eb86f3ac5c2c894527c1106af427d5e56ef"
|
||||
},
|
||||
{
|
||||
"path": "soupsieve/__meta__.py",
|
||||
"bytes": 6766,
|
||||
"sha256": "527081dcdaa542b7fd73f34cd7414a06468a83407a7fc941684baf733567f091"
|
||||
},
|
||||
{
|
||||
"path": "soupsieve/css_match.py",
|
||||
"bytes": 66688,
|
||||
"sha256": "a7cfc9adffd7ee71a0263854c78c9efcea287a0e566e335135d268ebb76c6b01"
|
||||
},
|
||||
{
|
||||
"path": "soupsieve/css_parser.py",
|
||||
"bytes": 51540,
|
||||
"sha256": "68be2f5dd01f7ad7ced717ef4250de7979436ec49cf845b88ce496c4fe1079e1"
|
||||
},
|
||||
{
|
||||
"path": "soupsieve/css_types.py",
|
||||
"bytes": 16274,
|
||||
"sha256": "e3ef6e7c94e45bd68f02e25cfc334083d31e4c773ddd21ef4b4d19c91e1b7568"
|
||||
},
|
||||
{
|
||||
"path": "soupsieve/pretty.py",
|
||||
"bytes": 4362,
|
||||
"sha256": "89233e34a0b3aee2500b012b8904fbd8bac5e2c971b226fb4c1e79d87d9bb2a0"
|
||||
},
|
||||
{
|
||||
"path": "soupsieve/py.typed",
|
||||
"bytes": 0,
|
||||
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
||||
},
|
||||
{
|
||||
"path": "soupsieve/util.py",
|
||||
"bytes": 3373,
|
||||
"sha256": "7e5a6da8baba9fcba4760fb15a6055c826b18be6ff0a2614517065b54ad07cbb"
|
||||
},
|
||||
{
|
||||
"path": "soupsieve-3.0.4.dist-info/METADATA",
|
||||
"bytes": 4389,
|
||||
"sha256": "548d71d83acf92c9206af9b8bac48271f34d2cdd3f6c6b4237c88bad6fee09fd"
|
||||
},
|
||||
{
|
||||
"path": "soupsieve-3.0.4.dist-info/WHEEL",
|
||||
"bytes": 87,
|
||||
"sha256": "5b77e4a649bbfb07fdbc123967eeecd1e5a478cfaca6eefc23c35e6fdf037848"
|
||||
},
|
||||
{
|
||||
"path": "soupsieve-3.0.4.dist-info/licenses/LICENSE.md",
|
||||
"bytes": 1096,
|
||||
"sha256": "76a0acdb98c3a63681e20b6f096699ef8cad5fb35d56eef8387e0fa71d797a9a"
|
||||
},
|
||||
{
|
||||
"path": "typing_extensions-4.16.0.dist-info/METADATA",
|
||||
"bytes": 3310,
|
||||
"sha256": "b05084ca1d50879865178d9fff9fabeab61bdfb1f361bfbde95421ffc8f9be46"
|
||||
},
|
||||
{
|
||||
"path": "typing_extensions-4.16.0.dist-info/WHEEL",
|
||||
"bytes": 82,
|
||||
"sha256": "1b68144734c4b66791f27add5d425f3620775585718a03d0f9b110ba3a4d88db"
|
||||
},
|
||||
{
|
||||
"path": "typing_extensions-4.16.0.dist-info/licenses/LICENSE",
|
||||
"bytes": 13936,
|
||||
"sha256": "3b2f81fe21d181c499c59a256c8e1968455d6689d269aa85373bfb6af41da3bf"
|
||||
},
|
||||
{
|
||||
"path": "typing_extensions.py",
|
||||
"bytes": 165012,
|
||||
"sha256": "4040ca1a1ecbee00d1385c12a93084d1c5bd46f0b774f07e5ae7e91c4f55e696"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
Metadata-Version: 2.5
|
||||
Name: soupsieve
|
||||
Version: 3.0.4
|
||||
Summary: A modern CSS selector implementation for Beautiful Soup.
|
||||
Project-URL: Homepage, https://github.com/facelessuser/soupsieve
|
||||
Author-email: Isaac Muse <Isaac.Muse@gmail.com>
|
||||
License-Expression: MIT
|
||||
License-File: LICENSE.md
|
||||
Keywords: CSS,HTML,XML,filter,query,selector,soup
|
||||
Classifier: Development Status :: 5 - Production/Stable
|
||||
Classifier: Environment :: Console
|
||||
Classifier: Intended Audience :: Developers
|
||||
Classifier: License :: OSI Approved :: MIT License
|
||||
Classifier: Operating System :: OS Independent
|
||||
Classifier: Programming Language :: Python :: 3
|
||||
Classifier: Programming Language :: Python :: 3.11
|
||||
Classifier: Programming Language :: Python :: 3.12
|
||||
Classifier: Programming Language :: Python :: 3.13
|
||||
Classifier: Programming Language :: Python :: 3.14
|
||||
Classifier: Programming Language :: Python :: 3.15
|
||||
Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
|
||||
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
||||
Classifier: Typing :: Typed
|
||||
Requires-Python: >=3.11.5
|
||||
Description-Content-Type: text/markdown
|
||||
|
||||
[![Donate via PayPal][donate-image]][donate-link]
|
||||
[![Coverage Status][codecov-image]][codecov-link]
|
||||
[![PyPI Version][pypi-image]][pypi-link]
|
||||
[![PyPI Downloads][pypi-down]][pypi-link]
|
||||
[![PyPI - Python Version][python-image]][pypi-link]
|
||||
[![License][license-image-mit]][license-link]
|
||||
|
||||
# Soup Sieve
|
||||
|
||||
## Overview
|
||||
|
||||
Soup Sieve is a CSS selector library designed to be used with [Beautiful Soup 4][bs4]. It aims to provide selecting,
|
||||
matching, and filtering using modern CSS selectors. Soup Sieve currently provides selectors from the CSS level 1
|
||||
specifications up through the latest CSS level 4 drafts and beyond (though some are not yet implemented).
|
||||
|
||||
Soup Sieve was written with the intent to replace Beautiful Soup's builtin select feature, and as of Beautiful Soup
|
||||
version 4.7.0, it now is :confetti_ball:. Soup Sieve can also be imported in order to use its API directly for
|
||||
more controlled, specialized parsing.
|
||||
|
||||
Soup Sieve has implemented most of the CSS selectors up through the latest CSS draft specifications, though there are a
|
||||
number that don't make sense in a non-browser environment. Selectors that cannot provide meaningful functionality simply
|
||||
do not match anything. Some of the supported selectors are:
|
||||
|
||||
- `.classes`
|
||||
- `#ids`
|
||||
- `[attributes=value]`
|
||||
- `parent child`
|
||||
- `parent > child`
|
||||
- `sibling ~ sibling`
|
||||
- `sibling + sibling`
|
||||
- `:not(element.class, element2.class)`
|
||||
- `:is(element.class, element2.class)`
|
||||
- `parent:has(> child)`
|
||||
- and [many more](https://facelessuser.github.io/soupsieve/selectors/)
|
||||
|
||||
|
||||
## Installation
|
||||
|
||||
You must have Beautiful Soup already installed:
|
||||
|
||||
```console
|
||||
$ pip install beautifulsoup4
|
||||
```
|
||||
|
||||
In most cases, assuming you've installed version 4.7.0, that should be all you need to do, but if you've installed via
|
||||
some alternative method, and Soup Sieve is not automatically installed, you can install it directly:
|
||||
|
||||
```console
|
||||
$ pip install soupsieve
|
||||
```
|
||||
|
||||
If you want to manually install it from source, first ensure that [`build`](https://pypi.org/project/build/) is
|
||||
installed:
|
||||
|
||||
```console
|
||||
$ pip install build
|
||||
```
|
||||
|
||||
Then navigate to the root of the project and build the wheel and install (replacing `<ver>` with the current version):
|
||||
|
||||
```console
|
||||
$ python -m build -w
|
||||
$ pip install dist/soupsieve-<ver>-py3-none-any.whl
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
Documentation is found here: https://facelessuser.github.io/soupsieve/.
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
|
||||
[bs4]: https://beautiful-soup-4.readthedocs.io/en/latest/#
|
||||
[codecov-image]: https://img.shields.io/codecov/c/github/facelessuser/soupsieve/master.svg?logo=codecov&logoColor=aaaaaa&labelColor=333333
|
||||
[codecov-link]: https://codecov.io/github/facelessuser/soupsieve
|
||||
[pypi-image]: https://img.shields.io/pypi/v/soupsieve.svg?logo=pypi&logoColor=aaaaaa&labelColor=333333
|
||||
[pypi-down]: https://img.shields.io/pypi/dm/soupsieve.svg?logo=pypi&logoColor=aaaaaa&labelColor=333333
|
||||
[pypi-link]: https://pypi.python.org/pypi/soupsieve
|
||||
[python-image]: https://img.shields.io/pypi/pyversions/soupsieve?logo=python&logoColor=aaaaaa&labelColor=333333
|
||||
[license-image-mit]: https://img.shields.io/badge/license-MIT-blue.svg?labelColor=333333
|
||||
[license-link]: https://github.com/facelessuser/soupsieve/blob/main/LICENSE.md
|
||||
[donate-image]: https://img.shields.io/badge/Donate-PayPal-3fabd1?logo=paypal
|
||||
[donate-link]: https://www.paypal.me/facelessuser
|
||||
@@ -0,0 +1,4 @@
|
||||
Wheel-Version: 1.0
|
||||
Generator: hatchling 1.32.4
|
||||
Root-Is-Purelib: true
|
||||
Tag: py3-none-any
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2018 - 2026 Isaac Muse <isaacmuse@gmail.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+234
@@ -0,0 +1,234 @@
|
||||
"""
|
||||
Soup Sieve.
|
||||
|
||||
A CSS selector filter for BeautifulSoup4.
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2018 Isaac Muse
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
from .__meta__ import __version__, __version_info__ # noqa: F401
|
||||
from . import css_parser as cp
|
||||
from . import css_match as cm
|
||||
from . import css_types as ct
|
||||
from .util import DEBUG, NOCACHE, NOSTRICT, SelectorSyntaxError # noqa: F401
|
||||
import bs4
|
||||
from typing import Any, Mapping, Iterator, Iterable, cast
|
||||
|
||||
__all__ = (
|
||||
'DEBUG', 'NOCACHE', 'NOSTRICT', 'SelectorSyntaxError', 'CustomSelectors', 'SoupSieve',
|
||||
'closest', 'compile', 'filter', 'iselect', 'match', 'select', 'select_one'
|
||||
)
|
||||
|
||||
SoupSieve = cm.SoupSieve
|
||||
CustomSelectors = ct.CustomSelectors
|
||||
|
||||
|
||||
def compile( # noqa: A001
|
||||
pattern: str,
|
||||
namespaces: dict[str, str] | None = None,
|
||||
flags: int = 0,
|
||||
*,
|
||||
custom: Mapping[str, str | ct.SelectorList] | None = None,
|
||||
ignore: Iterable[str] | None = None,
|
||||
max_selectors: int = cp.SELECTOR_LIMIT,
|
||||
**kwargs: Any
|
||||
) -> cm.SoupSieve:
|
||||
"""Compile CSS pattern."""
|
||||
|
||||
if isinstance(pattern, SoupSieve):
|
||||
if flags:
|
||||
raise ValueError("Cannot process 'flags' argument on a compiled selector list")
|
||||
elif namespaces is not None:
|
||||
raise ValueError("Cannot process 'namespaces' argument on a compiled selector list")
|
||||
elif custom is not None:
|
||||
raise ValueError("Cannot process 'custom' argument on a compiled selector list")
|
||||
return pattern
|
||||
|
||||
return cp._cached_css_compile(
|
||||
pattern,
|
||||
ct.Namespaces(namespaces) if namespaces is not None else namespaces,
|
||||
ct.CustomSelectors(
|
||||
cast('dict[str, str | ct.SelectorList]', custom), max_selectors=max_selectors
|
||||
) if custom is not None and not isinstance(custom, ct.CustomSelectors) else custom,
|
||||
tuple(i.lower() for i in ignore) if ignore is not None else ignore,
|
||||
flags,
|
||||
max_selectors
|
||||
)
|
||||
|
||||
|
||||
def purge() -> None:
|
||||
"""Purge cached patterns."""
|
||||
|
||||
cp._purge_cache()
|
||||
|
||||
|
||||
def closest(
|
||||
select: str,
|
||||
tag: bs4.Tag,
|
||||
namespaces: dict[str, str] | None = None,
|
||||
flags: int = 0,
|
||||
*,
|
||||
custom: Mapping[str, str | ct.SelectorList] | None = None,
|
||||
ignore: Iterable[str] | None = None,
|
||||
max_selectors: int = cp.SELECTOR_LIMIT,
|
||||
**kwargs: Any
|
||||
) -> bs4.Tag | None:
|
||||
"""Match closest ancestor."""
|
||||
|
||||
return compile(
|
||||
select,
|
||||
namespaces,
|
||||
flags,
|
||||
custom=custom,
|
||||
ignore=ignore,
|
||||
max_selectors=max_selectors,
|
||||
**kwargs
|
||||
).closest(tag)
|
||||
|
||||
|
||||
def match(
|
||||
select: str,
|
||||
tag: bs4.Tag,
|
||||
namespaces: dict[str, str] | None = None,
|
||||
flags: int = 0,
|
||||
*,
|
||||
custom: Mapping[str, str | ct.SelectorList] | None = None,
|
||||
ignore: Iterable[str] | None = None,
|
||||
max_selectors: int = cp.SELECTOR_LIMIT,
|
||||
**kwargs: Any
|
||||
) -> bool:
|
||||
"""Match node."""
|
||||
|
||||
return compile(
|
||||
select,
|
||||
namespaces,
|
||||
flags,
|
||||
custom=custom,
|
||||
ignore=ignore,
|
||||
max_selectors=max_selectors,
|
||||
**kwargs
|
||||
).match(tag)
|
||||
|
||||
|
||||
def filter( # noqa: A001
|
||||
select: str,
|
||||
iterable: Iterable[bs4.Tag],
|
||||
namespaces: dict[str, str] | None = None,
|
||||
flags: int = 0,
|
||||
*,
|
||||
custom: Mapping[str, str | ct.SelectorList] | None = None,
|
||||
ignore: Iterable[str] | None = None,
|
||||
max_selectors: int = cp.SELECTOR_LIMIT,
|
||||
**kwargs: Any
|
||||
) -> list[bs4.Tag]:
|
||||
"""Filter list of nodes."""
|
||||
|
||||
return compile(
|
||||
select,
|
||||
namespaces,
|
||||
flags,
|
||||
custom=custom,
|
||||
ignore=ignore,
|
||||
max_selectors=max_selectors,
|
||||
**kwargs
|
||||
).filter(iterable)
|
||||
|
||||
|
||||
def select_one(
|
||||
select: str,
|
||||
tag: bs4.Tag,
|
||||
namespaces: dict[str, str] | None = None,
|
||||
flags: int = 0,
|
||||
*,
|
||||
custom: Mapping[str, str | ct.SelectorList] | None = None,
|
||||
ignore: Iterable[str] | None = None,
|
||||
max_selectors: int = cp.SELECTOR_LIMIT,
|
||||
**kwargs: Any
|
||||
) -> bs4.Tag | None:
|
||||
"""Select a single tag."""
|
||||
|
||||
return compile(
|
||||
select,
|
||||
namespaces,
|
||||
flags,
|
||||
custom=custom,
|
||||
ignore=ignore,
|
||||
max_selectors=max_selectors,
|
||||
**kwargs
|
||||
).select_one(tag)
|
||||
|
||||
|
||||
def select(
|
||||
select: str,
|
||||
tag: bs4.Tag,
|
||||
namespaces: dict[str, str] | None = None,
|
||||
limit: int = 0,
|
||||
flags: int = 0,
|
||||
*,
|
||||
custom: Mapping[str, str | ct.SelectorList] | None = None,
|
||||
ignore: Iterable[str] | None = None,
|
||||
max_selectors: int = cp.SELECTOR_LIMIT,
|
||||
**kwargs: Any
|
||||
) -> list[bs4.Tag]:
|
||||
"""Select the specified tags."""
|
||||
|
||||
return compile(
|
||||
select,
|
||||
namespaces,
|
||||
flags,
|
||||
custom=custom,
|
||||
ignore=ignore,
|
||||
max_selectors=max_selectors,
|
||||
**kwargs
|
||||
).select(tag, limit)
|
||||
|
||||
|
||||
def iselect(
|
||||
select: str,
|
||||
tag: bs4.Tag,
|
||||
namespaces: dict[str, str] | None = None,
|
||||
limit: int = 0,
|
||||
flags: int = 0,
|
||||
*,
|
||||
custom: Mapping[str, str | ct.SelectorList] | None = None,
|
||||
ignore: Iterable[str] | None = None,
|
||||
max_selectors: int = cp.SELECTOR_LIMIT,
|
||||
**kwargs: Any
|
||||
) -> Iterator[bs4.Tag]:
|
||||
"""Iterate the specified tags."""
|
||||
|
||||
yield from compile(
|
||||
select,
|
||||
namespaces,
|
||||
flags,
|
||||
custom=custom,
|
||||
ignore=ignore,
|
||||
max_selectors=max_selectors,
|
||||
**kwargs
|
||||
).iselect(tag, limit)
|
||||
|
||||
|
||||
def escape(ident: str) -> str:
|
||||
"""Escape identifier."""
|
||||
|
||||
return cp.escape(ident)
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
"""Meta related things."""
|
||||
from __future__ import annotations
|
||||
from collections import namedtuple
|
||||
import re
|
||||
|
||||
RE_VER = re.compile(
|
||||
r'''(?x)
|
||||
(?P<major>\d+)(?:\.(?P<minor>\d+))?(?:\.(?P<micro>\d+))?
|
||||
(?:(?P<type>a|b|rc)(?P<pre>\d+))?
|
||||
(?:\.post(?P<post>\d+))?
|
||||
(?:\.dev(?P<dev>\d+))?
|
||||
'''
|
||||
)
|
||||
|
||||
REL_MAP = {
|
||||
".dev": "",
|
||||
".dev-alpha": "a",
|
||||
".dev-beta": "b",
|
||||
".dev-candidate": "rc",
|
||||
"alpha": "a",
|
||||
"beta": "b",
|
||||
"candidate": "rc",
|
||||
"final": ""
|
||||
}
|
||||
|
||||
DEV_STATUS = {
|
||||
".dev": "2 - Pre-Alpha",
|
||||
".dev-alpha": "2 - Pre-Alpha",
|
||||
".dev-beta": "2 - Pre-Alpha",
|
||||
".dev-candidate": "2 - Pre-Alpha",
|
||||
"alpha": "3 - Alpha",
|
||||
"beta": "4 - Beta",
|
||||
"candidate": "4 - Beta",
|
||||
"final": "5 - Production/Stable"
|
||||
}
|
||||
|
||||
PRE_REL_MAP = {"a": 'alpha', "b": 'beta', "rc": 'candidate'}
|
||||
|
||||
|
||||
class Version(namedtuple("Version", ["major", "minor", "micro", "release", "pre", "post", "dev"])):
|
||||
"""
|
||||
Get the version (PEP 440).
|
||||
|
||||
A biased approach to the PEP 440 semantic version.
|
||||
|
||||
Provides a tuple structure which is sorted for comparisons `v1 > v2` etc.
|
||||
(major, minor, micro, release type, pre-release build, post-release build, development release build)
|
||||
Release types are named in is such a way they are comparable with ease.
|
||||
Accessors to check if a development, pre-release, or post-release build. Also provides accessor to get
|
||||
development status for setup files.
|
||||
|
||||
How it works (currently):
|
||||
|
||||
- You must specify a release type as either `final`, `alpha`, `beta`, or `candidate`.
|
||||
- To define a development release, you can use either `.dev`, `.dev-alpha`, `.dev-beta`, or `.dev-candidate`.
|
||||
The dot is used to ensure all development specifiers are sorted before `alpha`.
|
||||
You can specify a `dev` number for development builds, but do not have to as implicit development releases
|
||||
are allowed.
|
||||
- You must specify a `pre` value greater than zero if using a prerelease as this project (not PEP 440) does not
|
||||
allow implicit prereleases.
|
||||
- You can optionally set `post` to a value greater than zero to make the build a post release. While post releases
|
||||
are technically allowed in prereleases, it is strongly discouraged, so we are rejecting them. It should be
|
||||
noted that we do not allow `post0` even though PEP 440 does not restrict this. This project specifically
|
||||
does not allow implicit post releases.
|
||||
- It should be noted that we do not support epochs `1!` or local versions `+some-custom.version-1`.
|
||||
|
||||
Acceptable version releases:
|
||||
|
||||
```
|
||||
Version(1, 0, 0, "final") 1.0
|
||||
Version(1, 2, 0, "final") 1.2
|
||||
Version(1, 2, 3, "final") 1.2.3
|
||||
Version(1, 2, 0, ".dev-alpha", pre=4) 1.2a4
|
||||
Version(1, 2, 0, ".dev-beta", pre=4) 1.2b4
|
||||
Version(1, 2, 0, ".dev-candidate", pre=4) 1.2rc4
|
||||
Version(1, 2, 0, "final", post=1) 1.2.post1
|
||||
Version(1, 2, 3, ".dev") 1.2.3.dev0
|
||||
Version(1, 2, 3, ".dev", dev=1) 1.2.3.dev1
|
||||
```
|
||||
|
||||
"""
|
||||
|
||||
def __new__(
|
||||
cls,
|
||||
major: int, minor: int, micro: int, release: str = "final",
|
||||
pre: int = 0, post: int = 0, dev: int = 0
|
||||
) -> Version:
|
||||
"""Validate version info."""
|
||||
|
||||
# Ensure all parts are positive integers.
|
||||
for value in (major, minor, micro, pre, post):
|
||||
if not (isinstance(value, int) and value >= 0):
|
||||
raise ValueError("All version parts except 'release' should be integers.")
|
||||
|
||||
if release not in REL_MAP:
|
||||
raise ValueError(f"'{release}' is not a valid release type.")
|
||||
|
||||
# Ensure valid pre-release (we do not allow implicit pre-releases).
|
||||
if ".dev-candidate" < release < "final":
|
||||
if pre == 0:
|
||||
raise ValueError("Implicit pre-releases not allowed.")
|
||||
elif dev:
|
||||
raise ValueError("Version is not a development release.")
|
||||
elif post:
|
||||
raise ValueError("Post-releases are not allowed with pre-releases.")
|
||||
|
||||
# Ensure valid development or development/pre release
|
||||
elif release < "alpha":
|
||||
if release > ".dev" and pre == 0:
|
||||
raise ValueError("Implicit pre-release not allowed.")
|
||||
elif post:
|
||||
raise ValueError("Post-releases are not allowed with pre-releases.")
|
||||
|
||||
# Ensure a valid normal release
|
||||
else:
|
||||
if pre:
|
||||
raise ValueError("Version is not a pre-release.")
|
||||
elif dev:
|
||||
raise ValueError("Version is not a development release.")
|
||||
|
||||
return super().__new__(cls, major, minor, micro, release, pre, post, dev)
|
||||
|
||||
def _is_pre(self) -> bool:
|
||||
"""Is prerelease."""
|
||||
|
||||
return bool(self.pre > 0)
|
||||
|
||||
def _is_dev(self) -> bool:
|
||||
"""Is development."""
|
||||
|
||||
return bool(self.release < "alpha")
|
||||
|
||||
def _is_post(self) -> bool:
|
||||
"""Is post."""
|
||||
|
||||
return bool(self.post > 0)
|
||||
|
||||
def _get_dev_status(self) -> str: # pragma: no cover
|
||||
"""Get development status string."""
|
||||
|
||||
return DEV_STATUS[self.release]
|
||||
|
||||
def _get_canonical(self) -> str:
|
||||
"""Get the canonical output string."""
|
||||
|
||||
# Assemble major, minor, micro version and append `pre`, `post`, or `dev` if needed..
|
||||
if self.micro == 0:
|
||||
ver = f"{self.major}.{self.minor}"
|
||||
else:
|
||||
ver = f"{self.major}.{self.minor}.{self.micro}"
|
||||
if self._is_pre():
|
||||
ver += f'{REL_MAP[self.release]}{self.pre}'
|
||||
if self._is_post():
|
||||
ver += f".post{self.post}"
|
||||
if self._is_dev():
|
||||
ver += f".dev{self.dev}"
|
||||
|
||||
return ver
|
||||
|
||||
|
||||
def parse_version(ver: str) -> Version:
|
||||
"""Parse version into a comparable Version tuple."""
|
||||
|
||||
m = RE_VER.match(ver)
|
||||
|
||||
if m is None:
|
||||
raise ValueError(f"'{ver}' is not a valid version")
|
||||
|
||||
# Handle major, minor, micro
|
||||
major = int(m.group('major'))
|
||||
minor = int(m.group('minor')) if m.group('minor') else 0
|
||||
micro = int(m.group('micro')) if m.group('micro') else 0
|
||||
|
||||
# Handle pre releases
|
||||
if m.group('type'):
|
||||
release = PRE_REL_MAP[m.group('type')]
|
||||
pre = int(m.group('pre'))
|
||||
else:
|
||||
release = "final"
|
||||
pre = 0
|
||||
|
||||
# Handle development releases
|
||||
dev = m.group('dev') if m.group('dev') else 0
|
||||
if m.group('dev'):
|
||||
dev = int(m.group('dev'))
|
||||
release = '.dev-' + release if pre else '.dev'
|
||||
else:
|
||||
dev = 0
|
||||
|
||||
# Handle post
|
||||
post = int(m.group('post')) if m.group('post') else 0
|
||||
|
||||
return Version(major, minor, micro, release, pre, post, dev)
|
||||
|
||||
|
||||
__version_info__ = Version(3, 0, 4, "final")
|
||||
__version__ = __version_info__._get_canonical()
|
||||
+1793
File diff suppressed because it is too large.
Load diff
+1462
File diff suppressed because it is too large.
Load diff
+572
@@ -0,0 +1,572 @@
|
||||
"""CSS selector structure items."""
|
||||
from __future__ import annotations
|
||||
from enum import Enum
|
||||
import copyreg
|
||||
from .pretty import pretty
|
||||
from typing import Any, Iterator, Pattern, Iterable, Mapping, TypeVar, overload
|
||||
|
||||
__all__ = (
|
||||
'Selector',
|
||||
'SelectorNull',
|
||||
'SelectorTag',
|
||||
'SelectorAttribute',
|
||||
'SelectorContains',
|
||||
'SelectorNth',
|
||||
'SelectorLang',
|
||||
'SelectorList',
|
||||
'Namespaces',
|
||||
'CustomSelectors'
|
||||
)
|
||||
|
||||
SEL_EMPTY = 0x1
|
||||
SEL_ROOT = 0x2
|
||||
SEL_DEFAULT = 0x4
|
||||
SEL_INDETERMINATE = 0x8
|
||||
SEL_SCOPE = 0x10
|
||||
SEL_DIR_LTR = 0x20
|
||||
SEL_DIR_RTL = 0x40
|
||||
SEL_IN_RANGE = 0x80
|
||||
SEL_OUT_OF_RANGE = 0x100
|
||||
SEL_DEFINED = 0x200
|
||||
SEL_PLACEHOLDER_SHOWN = 0x400
|
||||
|
||||
|
||||
def _repr_expand(value: Any) -> bool: # pragma: no cover
|
||||
"""Check if the value is an immutable object that uses the default representation."""
|
||||
|
||||
return isinstance(value, Immutable) and type(value).__repr__ is Immutable.__repr__
|
||||
|
||||
|
||||
def _repr_value(value: Any) -> Any: # pragma: no cover
|
||||
"""
|
||||
Return the representation of a leaf value, or the value itself if it must be expanded.
|
||||
|
||||
Immutable objects using the default representation are expanded, as are tuples containing them.
|
||||
"""
|
||||
|
||||
if _repr_expand(value) or (value.__class__ is tuple and any(_repr_expand(v) for v in value)):
|
||||
return value
|
||||
return repr(value)
|
||||
|
||||
|
||||
class Immutable:
|
||||
"""Immutable."""
|
||||
|
||||
__slots__: tuple[str, ...] = ('_hash',)
|
||||
|
||||
_hash: int
|
||||
|
||||
def __init__(self, **kwargs: Any) -> None:
|
||||
"""Initialize."""
|
||||
|
||||
temp = []
|
||||
for k, v in kwargs.items():
|
||||
temp.append(type(v))
|
||||
temp.append(v)
|
||||
super().__setattr__(k, v)
|
||||
super().__setattr__('_hash', hash(tuple(temp)))
|
||||
|
||||
@classmethod
|
||||
def __base__(cls) -> type[Immutable]:
|
||||
"""Get base class."""
|
||||
|
||||
return cls
|
||||
|
||||
def __eq__(self, other: Any) -> bool:
|
||||
"""Check equaling in a non-recursive manner."""
|
||||
|
||||
stack: list[tuple[Immutable, Any]] = [(self, other)]
|
||||
while stack:
|
||||
a, b = stack.pop()
|
||||
if a is b:
|
||||
continue
|
||||
|
||||
# The hash is derived from the content, so differing hashes cannot be equal.
|
||||
if not isinstance(b, a.__base__()) or a._hash != b._hash:
|
||||
return False
|
||||
|
||||
# Compare the attributes in the slot
|
||||
for key in a.__slots__[:-1]:
|
||||
x = getattr(a, key)
|
||||
y = getattr(b, key)
|
||||
if isinstance(x, Immutable):
|
||||
stack.append((x, y))
|
||||
elif x.__class__ is tuple and y.__class__ is tuple:
|
||||
if len(x) != len(y): # pragma: no cover
|
||||
return False
|
||||
for i, j in zip(x, y, strict=True):
|
||||
if isinstance(i, Immutable):
|
||||
stack.append((i, j))
|
||||
elif i != j: # pragma: no cover
|
||||
return False
|
||||
elif x != y:
|
||||
return False
|
||||
return True
|
||||
|
||||
def __ne__(self, other: Any) -> bool:
|
||||
"""Not equal."""
|
||||
|
||||
return not self.__eq__(other)
|
||||
|
||||
def __hash__(self) -> int:
|
||||
"""Hash."""
|
||||
|
||||
return self._hash
|
||||
|
||||
def __setattr__(self, name: str, value: Any) -> None:
|
||||
"""Prevent mutability."""
|
||||
|
||||
raise AttributeError(f"'{self.__class__.__name__}' is immutable")
|
||||
|
||||
def __repr__(self) -> str: # pragma: no cover
|
||||
"""
|
||||
Build a representation without using recursion.
|
||||
|
||||
Selectors can be nested very deeply, so build the representation of nested
|
||||
immutable objects with an explicit stack instead of recursing into their `__repr__`.
|
||||
Strings on the stack are output as is, other items are expanded into more items.
|
||||
"""
|
||||
|
||||
output: list[str] = []
|
||||
stack: list[Any] = [self]
|
||||
while stack:
|
||||
item = stack.pop()
|
||||
if item.__class__ is str:
|
||||
output.append(item)
|
||||
elif isinstance(item, Immutable):
|
||||
# Push parts in reverse so they are popped in order: `Name(key=value, ...)`
|
||||
stack.append(')')
|
||||
keys = item.__slots__[:-1]
|
||||
for index in range(len(keys) - 1, -1, -1):
|
||||
stack.append(_repr_value(getattr(item, keys[index])))
|
||||
stack.append(f'{keys[index]}=' if index == 0 else f', {keys[index]}=')
|
||||
stack.append(f'{item.__class__.__name__}(')
|
||||
else:
|
||||
# A tuple containing immutable objects: `(a,)` or `(a, b, ...)`
|
||||
stack.append(',)' if len(item) == 1 else ')')
|
||||
for index in range(len(item) - 1, -1, -1):
|
||||
stack.append(_repr_value(item[index]))
|
||||
if index:
|
||||
stack.append(', ')
|
||||
stack.append('(')
|
||||
return ''.join(output)
|
||||
|
||||
__str__ = __repr__
|
||||
|
||||
def pretty(self) -> None: # pragma: no cover
|
||||
"""Pretty print."""
|
||||
|
||||
print(pretty(self))
|
||||
|
||||
|
||||
class Selector(Immutable):
|
||||
"""Selector."""
|
||||
|
||||
__slots__ = (
|
||||
'tag', 'ids', 'classes', 'attributes', 'nth', 'selectors',
|
||||
'relation', 'rel_type', 'contains', 'lang', 'flags', '_hash'
|
||||
)
|
||||
|
||||
tag: SelectorTag | None
|
||||
ids: tuple[str, ...]
|
||||
classes: tuple[str, ...]
|
||||
attributes: tuple[SelectorAttribute, ...]
|
||||
nth: tuple[SelectorNth, ...]
|
||||
selectors: tuple[SelectorList, ...]
|
||||
relation: SelectorList
|
||||
rel_type: str | None
|
||||
contains: tuple[SelectorContains, ...]
|
||||
lang: tuple[SelectorLang, ...]
|
||||
flags: int
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tag: SelectorTag | None,
|
||||
ids: tuple[str, ...],
|
||||
classes: tuple[str, ...],
|
||||
attributes: tuple[SelectorAttribute, ...],
|
||||
nth: tuple[SelectorNth, ...],
|
||||
selectors: tuple[SelectorList, ...],
|
||||
relation: SelectorList,
|
||||
rel_type: str | None,
|
||||
contains: tuple[SelectorContains, ...],
|
||||
lang: tuple[SelectorLang, ...],
|
||||
flags: int
|
||||
):
|
||||
"""Initialize."""
|
||||
|
||||
super().__init__(
|
||||
tag=tag,
|
||||
ids=ids,
|
||||
classes=classes,
|
||||
attributes=attributes,
|
||||
nth=nth,
|
||||
selectors=selectors,
|
||||
relation=relation,
|
||||
rel_type=rel_type,
|
||||
contains=contains,
|
||||
lang=lang,
|
||||
flags=flags
|
||||
)
|
||||
|
||||
|
||||
class SelectorNull(Enum):
|
||||
"""Null Selector."""
|
||||
|
||||
null = 0
|
||||
|
||||
|
||||
Null = SelectorNull.null
|
||||
|
||||
|
||||
class SelectorTag(Immutable):
|
||||
"""Selector tag."""
|
||||
|
||||
__slots__ = ("name", "prefix", "_hash")
|
||||
|
||||
name: str
|
||||
prefix: str | None
|
||||
|
||||
def __init__(self, name: str, prefix: str | None) -> None:
|
||||
"""Initialize."""
|
||||
|
||||
super().__init__(name=name, prefix=prefix)
|
||||
|
||||
|
||||
class SelectorAttribute(Immutable):
|
||||
"""Selector attribute rule."""
|
||||
|
||||
__slots__ = ("attribute", "prefix", "pattern", "xml_type_pattern", "inverse", "_hash")
|
||||
|
||||
attribute: str
|
||||
prefix: str
|
||||
pattern: Pattern[str] | None
|
||||
xml_type_pattern: Pattern[str] | None
|
||||
inverse: bool
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
attribute: str,
|
||||
prefix: str,
|
||||
pattern: Pattern[str] | None,
|
||||
xml_type_pattern: Pattern[str] | None,
|
||||
inverse: bool
|
||||
) -> None:
|
||||
"""Initialize."""
|
||||
|
||||
super().__init__(
|
||||
attribute=attribute,
|
||||
prefix=prefix,
|
||||
pattern=pattern,
|
||||
xml_type_pattern=xml_type_pattern,
|
||||
inverse=inverse
|
||||
)
|
||||
|
||||
|
||||
class SelectorContains(Immutable):
|
||||
"""Selector contains rule."""
|
||||
|
||||
__slots__ = ("text", "own", "_hash")
|
||||
|
||||
text: tuple[str, ...]
|
||||
own: bool
|
||||
|
||||
def __init__(self, text: Iterable[str], own: bool) -> None:
|
||||
"""Initialize."""
|
||||
|
||||
super().__init__(text=tuple(text), own=own)
|
||||
|
||||
|
||||
class SelectorNth(Immutable):
|
||||
"""Selector nth type."""
|
||||
|
||||
__slots__ = ("a", "n", "b", "of_type", "last", "selectors", "_hash")
|
||||
|
||||
a: int
|
||||
n: bool
|
||||
b: int
|
||||
of_type: bool
|
||||
last: bool
|
||||
selectors: SelectorList
|
||||
|
||||
def __init__(self, a: int, n: bool, b: int, of_type: bool, last: bool, selectors: SelectorList) -> None:
|
||||
"""Initialize."""
|
||||
|
||||
super().__init__(
|
||||
a=a,
|
||||
n=n,
|
||||
b=b,
|
||||
of_type=of_type,
|
||||
last=last,
|
||||
selectors=selectors
|
||||
)
|
||||
|
||||
|
||||
class SelectorLang(Immutable):
|
||||
"""Selector language rules."""
|
||||
|
||||
__slots__ = ("languages", "_hash",)
|
||||
|
||||
languages: tuple[str, ...]
|
||||
|
||||
def __init__(self, languages: Iterable[str]):
|
||||
"""Initialize."""
|
||||
|
||||
super().__init__(languages=tuple(languages))
|
||||
|
||||
def __iter__(self) -> Iterator[str]:
|
||||
"""Iterator."""
|
||||
|
||||
return iter(self.languages)
|
||||
|
||||
def __len__(self) -> int: # pragma: no cover
|
||||
"""Length."""
|
||||
|
||||
return len(self.languages)
|
||||
|
||||
def __getitem__(self, index: int) -> str: # pragma: no cover
|
||||
"""Get item."""
|
||||
|
||||
return self.languages[index]
|
||||
|
||||
|
||||
class SelectorList(Immutable):
|
||||
"""Selector list."""
|
||||
|
||||
__slots__ = ("selectors", "is_not", "is_html", "count", "_hash")
|
||||
|
||||
selectors: tuple[Selector | SelectorNull, ...]
|
||||
is_not: bool
|
||||
is_html: bool
|
||||
count: int
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
selectors: Iterable[Selector | SelectorNull] | None = None,
|
||||
is_not: bool = False,
|
||||
is_html: bool = False,
|
||||
count: int = 0,
|
||||
) -> None:
|
||||
"""Initialize."""
|
||||
|
||||
super().__init__(
|
||||
selectors=tuple(selectors) if selectors is not None else (),
|
||||
is_not=is_not,
|
||||
is_html=is_html,
|
||||
count=count
|
||||
)
|
||||
|
||||
def __iter__(self) -> Iterator[Selector | SelectorNull]:
|
||||
"""Iterator."""
|
||||
|
||||
return iter(self.selectors)
|
||||
|
||||
def __len__(self) -> int:
|
||||
"""Length."""
|
||||
|
||||
return len(self.selectors)
|
||||
|
||||
def __getitem__(self, index: int) -> Selector | SelectorNull:
|
||||
"""Get item."""
|
||||
|
||||
return self.selectors[index]
|
||||
|
||||
|
||||
KT = TypeVar('KT')
|
||||
VT = TypeVar('VT')
|
||||
RT = TypeVar('RT')
|
||||
|
||||
|
||||
class ImmutableDict(Mapping[KT, VT]):
|
||||
"""Hashable, immutable dictionary."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
arg: Mapping[KT, VT]
|
||||
) -> None:
|
||||
"""Initialize."""
|
||||
|
||||
self._d = dict(arg)
|
||||
self._hash = hash(tuple([(type(x), x, type(y), y) for x, y in sorted(self._d.items())]))
|
||||
|
||||
@overload
|
||||
def get(self, key: KT, /) -> VT | None:
|
||||
...
|
||||
|
||||
@overload
|
||||
def get(self, key: KT, /, default: VT) -> VT:
|
||||
...
|
||||
|
||||
@overload
|
||||
def get(self, key: KT, /, default: RT) -> VT | RT:
|
||||
...
|
||||
|
||||
def get(self, key: KT, /, default: RT | VT | None = None) -> VT | RT | None:
|
||||
"""Get value."""
|
||||
|
||||
return self._d.get(key, default)
|
||||
|
||||
def __iter__(self) -> Iterator[KT]:
|
||||
"""Iterator."""
|
||||
|
||||
return iter(self._d)
|
||||
|
||||
def __len__(self) -> int:
|
||||
"""Length."""
|
||||
|
||||
return len(self._d)
|
||||
|
||||
def __getitem__(self, key: KT) -> VT:
|
||||
"""Get item: `namespace['key']`."""
|
||||
|
||||
return self._d[key]
|
||||
|
||||
def __hash__(self) -> int:
|
||||
"""Hash."""
|
||||
|
||||
return self._hash
|
||||
|
||||
def __repr__(self) -> str: # pragma: no cover
|
||||
"""Representation."""
|
||||
|
||||
return f"{self._d!r}"
|
||||
|
||||
__str__ = __repr__
|
||||
|
||||
|
||||
class Namespaces(ImmutableDict[str, str]):
|
||||
"""Namespaces."""
|
||||
|
||||
def __init__(self, arg: Mapping[str, str]) -> None:
|
||||
"""Initialize."""
|
||||
|
||||
self._validate(arg)
|
||||
super().__init__(arg)
|
||||
|
||||
def _validate(self, arg: Mapping[str, str]) -> None:
|
||||
"""Validate arguments."""
|
||||
|
||||
if not all(isinstance(k, str) and isinstance(v, str) for k, v in arg.items()):
|
||||
raise TypeError(f'{self.__class__.__name__} keys and values must be strings')
|
||||
|
||||
|
||||
class CustomSelectors(ImmutableDict[str, SelectorList]):
|
||||
"""Custom selectors."""
|
||||
|
||||
def __init__(self, arg: Mapping[str, str | SelectorList], max_selectors: int | None = None) -> None:
|
||||
"""Initialize."""
|
||||
|
||||
from . import css_parser as cp
|
||||
|
||||
if max_selectors is None:
|
||||
max_selectors = cp.SELECTOR_LIMIT
|
||||
|
||||
self._d = {}
|
||||
for k, v in arg.items():
|
||||
if not isinstance(k, str):
|
||||
raise TypeError(f'{self.__class__.__name__} keys must be strings')
|
||||
# Validate key
|
||||
k = cp.css_unescape(k).lower()
|
||||
if k in self._d:
|
||||
raise KeyError(f'Custom selector {k} was defined twice')
|
||||
if cp.RE_CUSTOM.match(k) is None:
|
||||
raise cp.SelectorSyntaxError(f"The name '{k}' is not a valid custom pseudo-class name")
|
||||
# Compile value
|
||||
if isinstance(v, str):
|
||||
v = cp.CSSParser(v, max_selectors=max_selectors, custom=self._d).process_selectors(flags=cp.FLG_PSEUDO)
|
||||
elif not isinstance(v, SelectorList):
|
||||
raise TypeError(f"Custom selector values must be either 'str' or 'SelectorList', not {type(v)}")
|
||||
# Monitor count
|
||||
max_selectors -= v.count
|
||||
self._d[k] = v
|
||||
self._hash = hash(tuple([(x, y) for x, y in sorted(self._d.items())] + [max_selectors]))
|
||||
|
||||
|
||||
def _pickle(p: Immutable) -> Any:
|
||||
"""
|
||||
Reduce an immutable object for pickling.
|
||||
|
||||
Selectors can be nested very deeply, and pickling them object by object would
|
||||
recurse for each level. Instead, flatten the entire structure into a table of
|
||||
nodes, children before parents, where nested immutable objects are replaced by
|
||||
their index in the table. As the table only contains leaf values, neither
|
||||
pickling nor unpickling needs to recurse.
|
||||
|
||||
Each node is `(class, args, refs)`. A ref is either the index of an argument that
|
||||
is an immutable object, or `(index, positions)` for an argument that is a tuple
|
||||
containing immutable objects at the given positions.
|
||||
"""
|
||||
|
||||
indexes: dict[int, int] = {}
|
||||
nodes: list[tuple[type[Immutable], tuple[Any, ...], tuple[Any, ...]]] = []
|
||||
stack: list[tuple[Immutable, list[Any] | None]] = [(p, None)]
|
||||
|
||||
while stack:
|
||||
obj, values = stack.pop()
|
||||
if id(obj) in indexes:
|
||||
continue
|
||||
|
||||
# Queue up children to be processed before the parent.
|
||||
if values is None:
|
||||
values = [getattr(obj, s) for s in obj.__slots__[:-1]]
|
||||
stack.append((obj, values))
|
||||
for value in values:
|
||||
if isinstance(value, Immutable):
|
||||
stack.append((value, None))
|
||||
elif value.__class__ is tuple:
|
||||
stack.extend((v, None) for v in value if isinstance(v, Immutable))
|
||||
continue
|
||||
|
||||
# All children have been processed, replace them with their index.
|
||||
refs: list[Any] = []
|
||||
for i, value in enumerate(values):
|
||||
if isinstance(value, Immutable):
|
||||
values[i] = indexes[id(value)]
|
||||
refs.append(i)
|
||||
elif value.__class__ is tuple:
|
||||
positions = [j for j, v in enumerate(value) if isinstance(v, Immutable)]
|
||||
if positions:
|
||||
items = list(value)
|
||||
for j in positions:
|
||||
items[j] = indexes[id(items[j])]
|
||||
values[i] = tuple(items)
|
||||
refs.append((i, tuple(positions)))
|
||||
|
||||
indexes[id(obj)] = len(nodes)
|
||||
nodes.append((obj.__base__(), tuple(values), tuple(refs)))
|
||||
|
||||
return _unpickle, (tuple(nodes),)
|
||||
|
||||
|
||||
def _unpickle(nodes: tuple[tuple[type[Immutable], tuple[Any, ...], tuple[Any, ...]], ...]) -> Immutable:
|
||||
"""Rebuild an immutable object from the flattened node table created by `_pickle`."""
|
||||
|
||||
objs: list[Immutable] = []
|
||||
for cls, args, refs in nodes:
|
||||
values = list(args)
|
||||
for ref in refs:
|
||||
if isinstance(ref, int):
|
||||
values[ref] = objs[values[ref]]
|
||||
else:
|
||||
i, positions = ref
|
||||
items = list(values[i])
|
||||
for j in positions:
|
||||
items[j] = objs[items[j]]
|
||||
values[i] = tuple(items)
|
||||
objs.append(cls(*values))
|
||||
return objs[-1]
|
||||
|
||||
|
||||
def pickle_register(obj: Any) -> None:
|
||||
"""Allow object to be pickled."""
|
||||
|
||||
copyreg.pickle(obj, _pickle)
|
||||
|
||||
|
||||
pickle_register(Selector)
|
||||
pickle_register(SelectorTag)
|
||||
pickle_register(SelectorAttribute)
|
||||
pickle_register(SelectorContains)
|
||||
pickle_register(SelectorNth)
|
||||
pickle_register(SelectorLang)
|
||||
pickle_register(SelectorList)
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
"""
|
||||
Format a pretty string of a `SoupSieve` object for easy debugging.
|
||||
|
||||
This won't necessarily support all types and such, and definitely
|
||||
not support custom outputs.
|
||||
|
||||
It is mainly geared towards our types as the `SelectorList`
|
||||
object is a beast to look at without some indentation and newlines.
|
||||
The format and various output types is fairly known (though it
|
||||
hasn't been tested extensively to make sure we aren't missing corners).
|
||||
|
||||
Example:
|
||||
-------
|
||||
```
|
||||
>>> import soupsieve as sv
|
||||
>>> sv.compile('this > that.class[name=value]').selectors.pretty()
|
||||
SelectorList(
|
||||
selectors=(
|
||||
Selector(
|
||||
tag=SelectorTag(
|
||||
name='that',
|
||||
prefix=None),
|
||||
ids=(),
|
||||
classes=(
|
||||
'class',
|
||||
),
|
||||
attributes=(
|
||||
SelectorAttribute(
|
||||
attribute='name',
|
||||
prefix='',
|
||||
pattern=re.compile(
|
||||
'^value$'),
|
||||
xml_type_pattern=None),
|
||||
),
|
||||
nth=(),
|
||||
selectors=(),
|
||||
relation=SelectorList(
|
||||
selectors=(
|
||||
Selector(
|
||||
tag=SelectorTag(
|
||||
name='this',
|
||||
prefix=None),
|
||||
ids=(),
|
||||
classes=(),
|
||||
attributes=(),
|
||||
nth=(),
|
||||
selectors=(),
|
||||
relation=SelectorList(
|
||||
selectors=(),
|
||||
is_not=False,
|
||||
is_html=False),
|
||||
rel_type='>',
|
||||
contains=(),
|
||||
lang=(),
|
||||
flags=0),
|
||||
),
|
||||
is_not=False,
|
||||
is_html=False),
|
||||
rel_type=None,
|
||||
contains=(),
|
||||
lang=(),
|
||||
flags=0),
|
||||
),
|
||||
is_not=False,
|
||||
is_html=False)
|
||||
```
|
||||
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
RE_CLASS = re.compile(r'(?i)[a-z_][_a-z\d.]+\(')
|
||||
RE_PARAM = re.compile(r'(?i)[_a-z][_a-z\d]+=')
|
||||
RE_EMPTY = re.compile(r'\(\)|\[\]|\{\}')
|
||||
RE_LSTRT = re.compile(r'\[')
|
||||
RE_DSTRT = re.compile(r'\{')
|
||||
RE_TSTRT = re.compile(r'\(')
|
||||
RE_LEND = re.compile(r'\]')
|
||||
RE_DEND = re.compile(r'\}')
|
||||
RE_TEND = re.compile(r'\)')
|
||||
RE_INT = re.compile(r'\d+')
|
||||
RE_KWORD = re.compile(r'(?i)[_a-z][_a-z\d.]+')
|
||||
RE_DQSTR = re.compile(r'"(?:\\.|[^"\\])*"')
|
||||
RE_SQSTR = re.compile(r"'(?:\\.|[^'\\])*'")
|
||||
RE_SEP = re.compile(r'\s*(,)\s*')
|
||||
RE_DSEP = re.compile(r'\s*(:)\s*')
|
||||
RE_PSEP = re.compile(r'\s*(\|)\s*')
|
||||
|
||||
TOKENS = {
|
||||
'class': RE_CLASS,
|
||||
'param': RE_PARAM,
|
||||
'empty': RE_EMPTY,
|
||||
'lstrt': RE_LSTRT,
|
||||
'dstrt': RE_DSTRT,
|
||||
'tstrt': RE_TSTRT,
|
||||
'lend': RE_LEND,
|
||||
'dend': RE_DEND,
|
||||
'tend': RE_TEND,
|
||||
'sqstr': RE_SQSTR,
|
||||
'sep': RE_SEP,
|
||||
'dsep': RE_DSEP,
|
||||
'psep': RE_PSEP,
|
||||
'int': RE_INT,
|
||||
'kword': RE_KWORD,
|
||||
'dqstr': RE_DQSTR
|
||||
}
|
||||
|
||||
|
||||
def pretty(obj: Any) -> str: # pragma: no cover
|
||||
"""Make the object output string pretty."""
|
||||
|
||||
sel = str(obj)
|
||||
index = 0
|
||||
end = len(sel) - 1
|
||||
indent = 0
|
||||
output = []
|
||||
|
||||
while index <= end:
|
||||
m = None
|
||||
for k, v in TOKENS.items():
|
||||
m = v.match(sel, index)
|
||||
|
||||
if m:
|
||||
name = k
|
||||
index = m.end(0)
|
||||
if name in ('class', 'lstrt', 'dstrt', 'tstrt'):
|
||||
indent += 4
|
||||
output.append(f'{m.group(0)}\n{" " * indent}')
|
||||
elif name in ('param', 'int', 'kword', 'sqstr', 'dqstr', 'empty'):
|
||||
output.append(m.group(0))
|
||||
elif name in ('lend', 'dend', 'tend'):
|
||||
indent -= 4
|
||||
output.append(m.group(0))
|
||||
elif name in ('sep',):
|
||||
output.append(f'{m.group(1)}\n{" " * indent}')
|
||||
elif name in ('dsep',):
|
||||
output.append(f'{m.group(1)} ')
|
||||
elif name in ('psep'):
|
||||
output.append(f' {m.group(1)} ')
|
||||
break
|
||||
|
||||
# We shouldn't hit this, but if we do, store unrecognized character
|
||||
if m is None: # pragma: no cover
|
||||
output.append(sel[index])
|
||||
index += 1
|
||||
|
||||
return ''.join(output)
|
||||
Whitespace-only changes.
+119
@@ -0,0 +1,119 @@
|
||||
"""Utility."""
|
||||
from __future__ import annotations
|
||||
from functools import wraps, lru_cache
|
||||
import warnings
|
||||
import re
|
||||
from typing import Callable, Any
|
||||
|
||||
DEBUG = 0x00001
|
||||
NOCACHE = 0x00002
|
||||
NOSTRICT = 0x00004
|
||||
|
||||
RE_PATTERN_LINE_SPLIT = re.compile(r'(?:\r\n|(?!\r\n)[\n\r])|$')
|
||||
|
||||
UC_A = ord('A')
|
||||
UC_Z = ord('Z')
|
||||
|
||||
|
||||
@lru_cache(maxsize=512)
|
||||
def lower(string: str) -> str:
|
||||
"""Lower."""
|
||||
|
||||
new_string = []
|
||||
for c in string:
|
||||
o = ord(c)
|
||||
new_string.append(chr(o + 32) if UC_A <= o <= UC_Z else c)
|
||||
return ''.join(new_string)
|
||||
|
||||
|
||||
class SelectorSyntaxError(Exception):
|
||||
"""Syntax error in a CSS selector."""
|
||||
|
||||
def __init__(self, msg: str, pattern: str | None = None, index: int | None = None) -> None:
|
||||
"""Initialize."""
|
||||
|
||||
self.line = None
|
||||
self.col = None
|
||||
self.context = None
|
||||
|
||||
if pattern is not None and index is not None:
|
||||
# Format pattern to show line and column position
|
||||
self.context, self.line, self.col = get_pattern_context(pattern, index)
|
||||
msg = f'{msg}\n line {self.line}:\n{self.context}'
|
||||
|
||||
super().__init__(msg)
|
||||
|
||||
|
||||
def deprecated(message: str, stacklevel: int = 2) -> Callable[..., Any]: # pragma: no cover
|
||||
"""
|
||||
Raise a `DeprecationWarning` when wrapped function/method is called.
|
||||
|
||||
Usage:
|
||||
|
||||
@deprecated("This method will be removed in version X; use Y instead.")
|
||||
def some_method()"
|
||||
pass
|
||||
"""
|
||||
|
||||
def _wrapper(func: Callable[..., Any]) -> Callable[..., Any]:
|
||||
@wraps(func)
|
||||
def _deprecated_func(*args: Any, **kwargs: Any) -> Any:
|
||||
warnings.warn(
|
||||
f"'{func.__name__}' is deprecated. {message}",
|
||||
category=DeprecationWarning,
|
||||
stacklevel=stacklevel
|
||||
)
|
||||
return func(*args, **kwargs)
|
||||
return _deprecated_func
|
||||
return _wrapper
|
||||
|
||||
|
||||
def warn_deprecated(message: str, stacklevel: int = 2) -> None: # pragma: no cover
|
||||
"""Warn deprecated."""
|
||||
|
||||
warnings.warn(
|
||||
message,
|
||||
category=DeprecationWarning,
|
||||
stacklevel=stacklevel
|
||||
)
|
||||
|
||||
|
||||
def get_pattern_context(pattern: str, index: int) -> tuple[str, int, int]:
|
||||
"""Get the pattern context."""
|
||||
|
||||
last = 0
|
||||
current_line = 1
|
||||
col = 1
|
||||
text: list[str] = []
|
||||
line = 1
|
||||
offset: int | None = None
|
||||
|
||||
# Split pattern by newline and handle the text before the newline
|
||||
for m in RE_PATTERN_LINE_SPLIT.finditer(pattern):
|
||||
linetext = pattern[last:m.start(0)]
|
||||
if not len(m.group(0)) and not len(text):
|
||||
indent = ''
|
||||
offset = -1
|
||||
col = index - last + 1
|
||||
elif last <= index < m.end(0):
|
||||
indent = '--> '
|
||||
offset = (-1 if index > m.start(0) else 0) + 3
|
||||
col = index - last + 1
|
||||
else:
|
||||
indent = ' '
|
||||
offset = None
|
||||
if len(text):
|
||||
# Regardless of whether we are presented with `\r\n`, `\r`, or `\n`,
|
||||
# we will render the output with just `\n`. We will still log the column
|
||||
# correctly though.
|
||||
text.append('\n')
|
||||
text.append(f'{indent}{linetext}')
|
||||
if offset is not None:
|
||||
text.append('\n')
|
||||
text.append(' ' * (col + offset) + '^')
|
||||
line = current_line
|
||||
|
||||
current_line += 1
|
||||
last = m.end(0)
|
||||
|
||||
return ''.join(text), line, col
|
||||
@@ -0,0 +1,73 @@
|
||||
Metadata-Version: 2.4
|
||||
Name: typing_extensions
|
||||
Version: 4.16.0
|
||||
Summary: Backported and Experimental Type Hints for Python 3.9+
|
||||
Keywords: annotations,backport,checker,checking,function,hinting,hints,type,typechecking,typehinting,typehints,typing
|
||||
Author-email: "Guido van Rossum, Jukka Lehtosalo, Łukasz Langa, Michael Lee" <levkivskyi@gmail.com>
|
||||
Requires-Python: >=3.9
|
||||
Description-Content-Type: text/markdown
|
||||
License-Expression: PSF-2.0
|
||||
Classifier: Development Status :: 5 - Production/Stable
|
||||
Classifier: Environment :: Console
|
||||
Classifier: Intended Audience :: Developers
|
||||
Classifier: Operating System :: OS Independent
|
||||
Classifier: Programming Language :: Python :: 3
|
||||
Classifier: Programming Language :: Python :: 3 :: Only
|
||||
Classifier: Programming Language :: Python :: 3.9
|
||||
Classifier: Programming Language :: Python :: 3.10
|
||||
Classifier: Programming Language :: Python :: 3.11
|
||||
Classifier: Programming Language :: Python :: 3.12
|
||||
Classifier: Programming Language :: Python :: 3.13
|
||||
Classifier: Programming Language :: Python :: 3.14
|
||||
Classifier: Programming Language :: Python :: 3.15
|
||||
Classifier: Topic :: Software Development
|
||||
License-File: LICENSE
|
||||
Project-URL: Bug Tracker, https://github.com/python/typing_extensions/issues
|
||||
Project-URL: Changes, https://github.com/python/typing_extensions/blob/main/CHANGELOG.md
|
||||
Project-URL: Documentation, https://typing-extensions.readthedocs.io/
|
||||
Project-URL: Home, https://github.com/python/typing_extensions
|
||||
Project-URL: Q & A, https://github.com/python/typing/discussions
|
||||
Project-URL: Repository, https://github.com/python/typing_extensions
|
||||
|
||||
# Typing Extensions
|
||||
|
||||
[](https://gitter.im/python/typing)
|
||||
|
||||
[Documentation](https://typing-extensions.readthedocs.io/en/latest/#) –
|
||||
[PyPI](https://pypi.org/project/typing-extensions/)
|
||||
|
||||
## Overview
|
||||
|
||||
The `typing_extensions` module serves two related purposes:
|
||||
|
||||
- Enable use of new type system features on older Python versions. For example,
|
||||
`typing.TypeGuard` is new in Python 3.10, but `typing_extensions` allows
|
||||
users on previous Python versions to use it too.
|
||||
- Enable experimentation with new type system PEPs before they are accepted and
|
||||
added to the `typing` module.
|
||||
|
||||
`typing_extensions` is treated specially by static type checkers such as
|
||||
mypy and pyright. Objects defined in `typing_extensions` are treated the same
|
||||
way as equivalent forms in `typing`.
|
||||
|
||||
`typing_extensions` uses
|
||||
[Semantic Versioning](https://semver.org/). The
|
||||
major version will be incremented only for backwards-incompatible changes.
|
||||
Therefore, it's safe to depend
|
||||
on `typing_extensions` like this: `typing_extensions ~=x.y`,
|
||||
where `x.y` is the first version that includes all features you need.
|
||||
[This](https://packaging.python.org/en/latest/specifications/version-specifiers/#compatible-release)
|
||||
is equivalent to `typing_extensions >=x.y, <(x+1)`. Do not depend on `~= x.y.z`
|
||||
unless you really know what you're doing; that defeats the purpose of
|
||||
semantic versioning.
|
||||
|
||||
## Included items
|
||||
|
||||
See [the documentation](https://typing-extensions.readthedocs.io/en/latest/#) for a
|
||||
complete listing of module contents.
|
||||
|
||||
## Contributing
|
||||
|
||||
See [CONTRIBUTING.md](https://github.com/python/typing_extensions/blob/main/CONTRIBUTING.md)
|
||||
for how to contribute to `typing_extensions`.
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
Wheel-Version: 1.0
|
||||
Generator: flit 3.12.0
|
||||
Root-Is-Purelib: true
|
||||
Tag: py3-none-any
|
||||
+279
@@ -0,0 +1,279 @@
|
||||
A. HISTORY OF THE SOFTWARE
|
||||
==========================
|
||||
|
||||
Python was created in the early 1990s by Guido van Rossum at Stichting
|
||||
Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands
|
||||
as a successor of a language called ABC. Guido remains Python's
|
||||
principal author, although it includes many contributions from others.
|
||||
|
||||
In 1995, Guido continued his work on Python at the Corporation for
|
||||
National Research Initiatives (CNRI, see https://www.cnri.reston.va.us)
|
||||
in Reston, Virginia where he released several versions of the
|
||||
software.
|
||||
|
||||
In May 2000, Guido and the Python core development team moved to
|
||||
BeOpen.com to form the BeOpen PythonLabs team. In October of the same
|
||||
year, the PythonLabs team moved to Digital Creations, which became
|
||||
Zope Corporation. In 2001, the Python Software Foundation (PSF, see
|
||||
https://www.python.org/psf/) was formed, a non-profit organization
|
||||
created specifically to own Python-related Intellectual Property.
|
||||
Zope Corporation was a sponsoring member of the PSF.
|
||||
|
||||
All Python releases are Open Source (see https://opensource.org for
|
||||
the Open Source Definition). Historically, most, but not all, Python
|
||||
releases have also been GPL-compatible; the table below summarizes
|
||||
the various releases.
|
||||
|
||||
Release Derived Year Owner GPL-
|
||||
from compatible? (1)
|
||||
|
||||
0.9.0 thru 1.2 1991-1995 CWI yes
|
||||
1.3 thru 1.5.2 1.2 1995-1999 CNRI yes
|
||||
1.6 1.5.2 2000 CNRI no
|
||||
2.0 1.6 2000 BeOpen.com no
|
||||
1.6.1 1.6 2001 CNRI yes (2)
|
||||
2.1 2.0+1.6.1 2001 PSF no
|
||||
2.0.1 2.0+1.6.1 2001 PSF yes
|
||||
2.1.1 2.1+2.0.1 2001 PSF yes
|
||||
2.1.2 2.1.1 2002 PSF yes
|
||||
2.1.3 2.1.2 2002 PSF yes
|
||||
2.2 and above 2.1.1 2001-now PSF yes
|
||||
|
||||
Footnotes:
|
||||
|
||||
(1) GPL-compatible doesn't mean that we're distributing Python under
|
||||
the GPL. All Python licenses, unlike the GPL, let you distribute
|
||||
a modified version without making your changes open source. The
|
||||
GPL-compatible licenses make it possible to combine Python with
|
||||
other software that is released under the GPL; the others don't.
|
||||
|
||||
(2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
|
||||
because its license has a choice of law clause. According to
|
||||
CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
|
||||
is "not incompatible" with the GPL.
|
||||
|
||||
Thanks to the many outside volunteers who have worked under Guido's
|
||||
direction to make these releases possible.
|
||||
|
||||
|
||||
B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
|
||||
===============================================================
|
||||
|
||||
Python software and documentation are licensed under the
|
||||
Python Software Foundation License Version 2.
|
||||
|
||||
Starting with Python 3.8.6, examples, recipes, and other code in
|
||||
the documentation are dual licensed under the PSF License Version 2
|
||||
and the Zero-Clause BSD license.
|
||||
|
||||
Some software incorporated into Python is under different licenses.
|
||||
The licenses are listed with code falling under that license.
|
||||
|
||||
|
||||
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
|
||||
--------------------------------------------
|
||||
|
||||
1. This LICENSE AGREEMENT is between the Python Software Foundation
|
||||
("PSF"), and the Individual or Organization ("Licensee") accessing and
|
||||
otherwise using this software ("Python") in source or binary form and
|
||||
its associated documentation.
|
||||
|
||||
2. Subject to the terms and conditions of this License Agreement, PSF hereby
|
||||
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
|
||||
analyze, test, perform and/or display publicly, prepare derivative works,
|
||||
distribute, and otherwise use Python alone or in any derivative version,
|
||||
provided, however, that PSF's License Agreement and PSF's notice of copyright,
|
||||
i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
|
||||
2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Python Software Foundation;
|
||||
All Rights Reserved" are retained in Python alone or in any derivative version
|
||||
prepared by Licensee.
|
||||
|
||||
3. In the event Licensee prepares a derivative work that is based on
|
||||
or incorporates Python or any part thereof, and wants to make
|
||||
the derivative work available to others as provided herein, then
|
||||
Licensee hereby agrees to include in any such work a brief summary of
|
||||
the changes made to Python.
|
||||
|
||||
4. PSF is making Python available to Licensee on an "AS IS"
|
||||
basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
|
||||
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
|
||||
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
|
||||
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
|
||||
INFRINGE ANY THIRD PARTY RIGHTS.
|
||||
|
||||
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
|
||||
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
|
||||
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
|
||||
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
|
||||
|
||||
6. This License Agreement will automatically terminate upon a material
|
||||
breach of its terms and conditions.
|
||||
|
||||
7. Nothing in this License Agreement shall be deemed to create any
|
||||
relationship of agency, partnership, or joint venture between PSF and
|
||||
Licensee. This License Agreement does not grant permission to use PSF
|
||||
trademarks or trade name in a trademark sense to endorse or promote
|
||||
products or services of Licensee, or any third party.
|
||||
|
||||
8. By copying, installing or otherwise using Python, Licensee
|
||||
agrees to be bound by the terms and conditions of this License
|
||||
Agreement.
|
||||
|
||||
|
||||
BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
|
||||
-------------------------------------------
|
||||
|
||||
BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
|
||||
|
||||
1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
|
||||
office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
|
||||
Individual or Organization ("Licensee") accessing and otherwise using
|
||||
this software in source or binary form and its associated
|
||||
documentation ("the Software").
|
||||
|
||||
2. Subject to the terms and conditions of this BeOpen Python License
|
||||
Agreement, BeOpen hereby grants Licensee a non-exclusive,
|
||||
royalty-free, world-wide license to reproduce, analyze, test, perform
|
||||
and/or display publicly, prepare derivative works, distribute, and
|
||||
otherwise use the Software alone or in any derivative version,
|
||||
provided, however, that the BeOpen Python License is retained in the
|
||||
Software, alone or in any derivative version prepared by Licensee.
|
||||
|
||||
3. BeOpen is making the Software available to Licensee on an "AS IS"
|
||||
basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
|
||||
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
|
||||
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
|
||||
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
|
||||
INFRINGE ANY THIRD PARTY RIGHTS.
|
||||
|
||||
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
|
||||
SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
|
||||
AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
|
||||
DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
|
||||
|
||||
5. This License Agreement will automatically terminate upon a material
|
||||
breach of its terms and conditions.
|
||||
|
||||
6. This License Agreement shall be governed by and interpreted in all
|
||||
respects by the law of the State of California, excluding conflict of
|
||||
law provisions. Nothing in this License Agreement shall be deemed to
|
||||
create any relationship of agency, partnership, or joint venture
|
||||
between BeOpen and Licensee. This License Agreement does not grant
|
||||
permission to use BeOpen trademarks or trade names in a trademark
|
||||
sense to endorse or promote products or services of Licensee, or any
|
||||
third party. As an exception, the "BeOpen Python" logos available at
|
||||
http://www.pythonlabs.com/logos.html may be used according to the
|
||||
permissions granted on that web page.
|
||||
|
||||
7. By copying, installing or otherwise using the software, Licensee
|
||||
agrees to be bound by the terms and conditions of this License
|
||||
Agreement.
|
||||
|
||||
|
||||
CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
|
||||
---------------------------------------
|
||||
|
||||
1. This LICENSE AGREEMENT is between the Corporation for National
|
||||
Research Initiatives, having an office at 1895 Preston White Drive,
|
||||
Reston, VA 20191 ("CNRI"), and the Individual or Organization
|
||||
("Licensee") accessing and otherwise using Python 1.6.1 software in
|
||||
source or binary form and its associated documentation.
|
||||
|
||||
2. Subject to the terms and conditions of this License Agreement, CNRI
|
||||
hereby grants Licensee a nonexclusive, royalty-free, world-wide
|
||||
license to reproduce, analyze, test, perform and/or display publicly,
|
||||
prepare derivative works, distribute, and otherwise use Python 1.6.1
|
||||
alone or in any derivative version, provided, however, that CNRI's
|
||||
License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
|
||||
1995-2001 Corporation for National Research Initiatives; All Rights
|
||||
Reserved" are retained in Python 1.6.1 alone or in any derivative
|
||||
version prepared by Licensee. Alternately, in lieu of CNRI's License
|
||||
Agreement, Licensee may substitute the following text (omitting the
|
||||
quotes): "Python 1.6.1 is made available subject to the terms and
|
||||
conditions in CNRI's License Agreement. This Agreement together with
|
||||
Python 1.6.1 may be located on the internet using the following
|
||||
unique, persistent identifier (known as a handle): 1895.22/1013. This
|
||||
Agreement may also be obtained from a proxy server on the internet
|
||||
using the following URL: http://hdl.handle.net/1895.22/1013".
|
||||
|
||||
3. In the event Licensee prepares a derivative work that is based on
|
||||
or incorporates Python 1.6.1 or any part thereof, and wants to make
|
||||
the derivative work available to others as provided herein, then
|
||||
Licensee hereby agrees to include in any such work a brief summary of
|
||||
the changes made to Python 1.6.1.
|
||||
|
||||
4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
|
||||
basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
|
||||
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
|
||||
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
|
||||
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
|
||||
INFRINGE ANY THIRD PARTY RIGHTS.
|
||||
|
||||
5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
|
||||
1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
|
||||
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
|
||||
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
|
||||
|
||||
6. This License Agreement will automatically terminate upon a material
|
||||
breach of its terms and conditions.
|
||||
|
||||
7. This License Agreement shall be governed by the federal
|
||||
intellectual property law of the United States, including without
|
||||
limitation the federal copyright law, and, to the extent such
|
||||
U.S. federal law does not apply, by the law of the Commonwealth of
|
||||
Virginia, excluding Virginia's conflict of law provisions.
|
||||
Notwithstanding the foregoing, with regard to derivative works based
|
||||
on Python 1.6.1 that incorporate non-separable material that was
|
||||
previously distributed under the GNU General Public License (GPL), the
|
||||
law of the Commonwealth of Virginia shall govern this License
|
||||
Agreement only as to issues arising under or with respect to
|
||||
Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this
|
||||
License Agreement shall be deemed to create any relationship of
|
||||
agency, partnership, or joint venture between CNRI and Licensee. This
|
||||
License Agreement does not grant permission to use CNRI trademarks or
|
||||
trade name in a trademark sense to endorse or promote products or
|
||||
services of Licensee, or any third party.
|
||||
|
||||
8. By clicking on the "ACCEPT" button where indicated, or by copying,
|
||||
installing or otherwise using Python 1.6.1, Licensee agrees to be
|
||||
bound by the terms and conditions of this License Agreement.
|
||||
|
||||
ACCEPT
|
||||
|
||||
|
||||
CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
|
||||
--------------------------------------------------
|
||||
|
||||
Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
|
||||
The Netherlands. All rights reserved.
|
||||
|
||||
Permission to use, copy, modify, and distribute this software and its
|
||||
documentation for any purpose and without fee is hereby granted,
|
||||
provided that the above copyright notice appear in all copies and that
|
||||
both that copyright notice and this permission notice appear in
|
||||
supporting documentation, and that the name of Stichting Mathematisch
|
||||
Centrum or CWI not be used in advertising or publicity pertaining to
|
||||
distribution of the software without specific, written prior
|
||||
permission.
|
||||
|
||||
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
|
||||
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
|
||||
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
|
||||
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION
|
||||
----------------------------------------------------------------------
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
PERFORMANCE OF THIS SOFTWARE.
|
||||
+4422
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,20 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check exact vendored pure-Python source hashes before importing them."""
|
||||
from pathlib import Path
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
ROOT = Path(__file__).resolve().parent / 'vendor'
|
||||
manifest = json.loads((ROOT / 'manifest.json').read_text())
|
||||
expected = set()
|
||||
for item in manifest['files']:
|
||||
path = ROOT / item['path']
|
||||
path.resolve().relative_to(ROOT.resolve())
|
||||
assert path.is_file(), f"Missing vendored file: {item['path']}"
|
||||
assert hashlib.sha256(path.read_bytes()).hexdigest() == item['sha256'], f"Vendor hash mismatch: {item['path']}"
|
||||
expected.add(item['path'])
|
||||
actual = {p.relative_to(ROOT).as_posix() for p in ROOT.rglob('*')
|
||||
if p.is_file() and p.name != 'manifest.json' and '__pycache__' not in p.parts and p.suffix != '.pyc'}
|
||||
assert actual == expected, f'Unmanifested vendor files: {actual ^ expected}'
|
||||
print(json.dumps(dict(status='verified', files=len(expected),
|
||||
packages=[dict(name=p['distribution'], version=p['version']) for p in manifest['packages']]), indent=2))
|
||||
Reference in new issue
Block a user