Preskočiť na obsah

Príklad: poškodené stránky ​

Skutočné stránky nie sú vždy správne zapísané. Tento príklad pustí parsery na šesť testovacích stránok, z ktorých každá niečo porušuje, a vypíše, čo každý parser vrátil. Ani jeden nevyhodí výnimku.

Stránky ​

html
<html><head>
<title>Attributes in any order</title>
<meta content="Written content first" property="og:title">
<meta content="https://shop.example/p/42" property="og:url">
<meta property="og:site_name" content="Shop">
<meta property="og:description" content="">
<meta name="description" content="Empty og:description above">
</head></html>
html
<html><head>
<TITLE>Old CMS &amp; unclosed tags</TITLE>
<META NAME=description CONTENT="Upper case tags, unquoted attribute names">
<meta property=og:type content=website>
<div><p>no closing tags
html
<html><head>
<title>Two JSON-LD blocks, the first one broken</title>
<script type="application/ld+json">
{"@type": "NewsArticle", "headline": "Trailing comma",}
</script>
<script type='application/ld+json'>
{"@context": "https://schema.org", "@type": "BlogPosting", "headline": "The valid block", "author": "Ján Kráľ", "datePublished": "not a date"}
</script>
</head></html>
php
<?php

declare(strict_types=1);

// The built-in server sends .html files as UTF-8; this one page announces its real charset.
if (parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) === '/windows-1250.html') {
    header('Content-Type: text/html; charset=windows-1250');
    readfile(__DIR__ . '/windows-1250.html');
    return true;
}

return false;

no-charset.html je stránka v UTF-8 bez akejkoľvek deklarácie kódovania, windows-1250.html je v kódovaní Windows-1250 a deklaruje ho (súbor nie je platné UTF-8, preto ho tu neukazujeme; router.php ho posiela so zodpovedajúcim Content-Type) a empty.html je prázdny súbor.

Kód ​

php
<?php

declare(strict_types=1);

// Pages that are not well-formed, not UTF-8 or not there at all. The parsers never throw on
// bad input: they return what they could read, and a field they could not read is null.

require __DIR__ . '/vendor/autoload.php';

use Tomaj\Scraper\Meta;
use Tomaj\Scraper\Parser\OgDomParser;
use Tomaj\Scraper\Parser\OgParser;
use Tomaj\Scraper\Parser\SchemaParser;
use Tomaj\Scraper\Scraper;

$base = $argv[1] ?? 'http://127.0.0.1:8404';

$scraper = new Scraper(['timeout' => 5]);
$show = static function (string $label, Meta $meta, array $fields): void {
    echo "{$label}\n";
    foreach ($fields as $field) {
        $value = match ($field) {
            'authors' => implode(', ', array_map(static fn($author): ?string => $author->name(), $meta->getAuthors())),
            'published' => $meta->getPublishedTime()?->format(DATE_ATOM),
            default => $meta->{'get' . $field}(),
        };
        printf("  %-13s %s\n", $field, $value ?? '(null)');
    }
};

echo "== reversed.html: content before property, an empty content\n";
$scraper->parseUrl($base . '/reversed.html', []);
$fields = ['title', 'ogTitle', 'ogUrl', 'ogSiteName', 'ogDescription', 'description'];
$show('OgParser', $scraper->parse($scraper->getBody(), [new OgParser()]), $fields);
$show('OgDomParser', $scraper->parse($scraper->getBody(), [new OgDomParser()]), $fields);

echo "\n== unquoted.html: upper case tags, unquoted attributes, no closing tags\n";
$scraper->parseUrl($base . '/unquoted.html', []);
$fields = ['title', 'description', 'ogType'];
$show('OgParser', $scraper->parse($scraper->getBody(), [new OgParser()]), $fields);
$show('OgDomParser', $scraper->parse($scraper->getBody(), [new OgDomParser()]), $fields);

echo "\n== invalid-json-ld.html: the broken block is skipped\n";
$show('SchemaParser', $scraper->parseUrl($base . '/invalid-json-ld.html', [new SchemaParser()]), ['title', 'authors', 'published']);

echo "\n== no-charset.html: UTF-8 without a charset declaration\n";
$scraper->parseUrl($base . '/no-charset.html', []);
$show('OgParser', $scraper->parse($scraper->getBody(), [new OgParser()]), ['title']);
$show('OgDomParser', $scraper->parse($scraper->getBody(), [new OgDomParser()]), ['title']);

echo "\n== windows-1250.html: a declared legacy charset\n";
$scraper->parseUrl($base . '/windows-1250.html', []);
$html = $scraper->getBody();
// OgParser returns the bytes as they are: not valid UTF-8
$title = $scraper->parse($html, [new OgParser()])->getTitle() ?? '';
printf("OgParser\n  %-13s %s\n", 'valid UTF-8', preg_match('//u', $title) === 1 ? 'yes' : 'no');
// OgDomParser decodes the declared charset
$show('OgDomParser', $scraper->parse($html, [new OgDomParser()]), ['title', 'description']);
// convert the body yourself for OgParser and SchemaParser (mbstring has no Windows-1250, iconv has)
$utf8 = iconv('Windows-1250', 'UTF-8', $html);
$show('OgParser after iconv()', $scraper->parse((string) $utf8, [new OgParser()]), ['title', 'description']);

echo "\n== empty.html: an empty body\n";
$meta = $scraper->parseUrl($base . '/empty.html', [new SchemaParser(), new OgDomParser(), new OgParser()]);
$show('all three parsers', $meta, ['title', 'description', 'ogImage', 'authors']);

Výstup ​

text
== reversed.html: content before property, an empty content
OgParser
  title         Attributes in any order
  ogTitle       (null)
  ogUrl         (null)
  ogSiteName    Shop
  ogDescription (null)
  description   Empty og:description above
OgDomParser
  title         Attributes in any order
  ogTitle       Written content first
  ogUrl         https://shop.example/p/42
  ogSiteName    Shop
  ogDescription (null)
  description   Empty og:description above

== unquoted.html: upper case tags, unquoted attributes, no closing tags
OgParser
  title         Old CMS & unclosed tags
  description   (null)
  ogType        (null)
OgDomParser
  title         Old CMS & unclosed tags
  description   Upper case tags, unquoted attribute names
  ogType        website

== invalid-json-ld.html: the broken block is skipped
SchemaParser
  title         The valid block
  authors       Ján Kráľ
  published     (null)

== no-charset.html: UTF-8 without a charset declaration
OgParser
  title         Ľudovít Štúr – životopis
OgDomParser
  title         Ľudovít Štúr – životopis

== windows-1250.html: a declared legacy charset
OgParser
  valid UTF-8   no
OgDomParser
  title         Žltý kôň úpel ďábelské ódy
  description   Stránka v kódovaní windows-1250
OgParser after iconv()
  title         Žltý kôň úpel ďábelské ódy
  description   Stránka v kódovaní windows-1250

== empty.html: an empty body
all three parsers
  title         (null)
  description   (null)
  ogImage       (null)
  authors

Čo si všimnúť ​

  • reversed.html: OgParser vynechá tagy s content na začiatku. Keď je content pred property, OgParser tag neprečíta a pre og:title aj og:url vráti null; hodnotu susedného tagu nikdy nevezme. OgDomParser prečíta všetky tri. Preto je OgDomParser odporúčaný parser pre stránky, ktoré nemáte pod kontrolou; pozrite Výber parsera. Pre prázdny og:description oba parsery vrátia prázdny reťazec a Meta::merge() berie prázdny reťazec ako chýbajúcu hodnotu, preto je výsledok null.
  • unquoted.html: tagy veľkými písmenami a hodnoty atribútov bez úvodzoviek OgDomParser nevadia; OgParser potrebuje úvodzovky a nájde len titulok.
  • invalid-json-ld.html: blok s čiarkou na konci sa preskočí a použije sa ďalší blok. Autor zadaný ako obyčajný reťazec sa prečíta; "datePublished": "not a date" sa ignoruje.
  • no-charset.html: oba parsery vrátia správne UTF-8: OgParser bajty len odovzdá ďalej, OgDomParser číta dokumenty bez deklarácie ako UTF-8.
  • windows-1250.html: OgParser vráti bajty vo Windows-1250, ktoré nie sú platné UTF-8. OgDomParser deklarované kódovanie dekóduje. Ak telo najprv prevediete cez iconv(), OgParser to opraví (a opravilo by to aj SchemaParser); mb_convert_encoding() Windows-1250 nepodporuje.
  • empty.html: každé pole je null, každý zoznam prázdny.

Čo kontroluje CI ​

Každú hodnotu vyššie vrátane hodnôt null z OgParser pri reversed.html, takže zmena správania parserov na poškodenom vstupe sa prejaví ako zlyhaný príklad.