metainspector 5.21.2 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +37 -0
  3. data/README.md +215 -48
  4. data/lib/meta_inspector/attempt_timeout.rb +40 -0
  5. data/lib/meta_inspector/document.rb +101 -68
  6. data/lib/meta_inspector/errors.rb +5 -1
  7. data/lib/meta_inspector/html_encoding.rb +183 -0
  8. data/lib/meta_inspector/http_session.rb +74 -45
  9. data/lib/meta_inspector/image_downloader.rb +37 -24
  10. data/lib/meta_inspector/parser.rb +144 -34
  11. data/lib/meta_inspector/parsers/base.rb +7 -2
  12. data/lib/meta_inspector/parsers/head_links.rb +20 -28
  13. data/lib/meta_inspector/parsers/iframes.rb +2 -3
  14. data/lib/meta_inspector/parsers/images.rb +119 -70
  15. data/lib/meta_inspector/parsers/links.rb +19 -9
  16. data/lib/meta_inspector/parsers/meta_tags.rb +22 -31
  17. data/lib/meta_inspector/parsers/texts.rb +43 -33
  18. data/lib/meta_inspector/request.rb +67 -55
  19. data/lib/meta_inspector/url.rb +43 -19
  20. data/lib/meta_inspector/url_policy.rb +18 -11
  21. data/lib/meta_inspector/version.rb +1 -1
  22. data/lib/meta_inspector.rb +14 -13
  23. data/lib/metainspector.rb +1 -1
  24. data/meta_inspector.gemspec +1 -1
  25. data/spec/document_spec.rb +154 -56
  26. data/spec/meta_inspector/content_type_spec.rb +47 -0
  27. data/spec/meta_inspector/head_links_spec.rb +3 -3
  28. data/spec/meta_inspector/images_spec.rb +82 -1
  29. data/spec/meta_inspector/links_spec.rb +98 -2
  30. data/spec/meta_inspector/meta_inspector_spec.rb +3 -25
  31. data/spec/meta_inspector/meta_tags_spec.rb +53 -0
  32. data/spec/meta_inspector/texts_spec.rb +140 -3
  33. data/spec/meta_inspector/timeouts_spec.rb +107 -0
  34. data/spec/noscript_spec.rb +179 -0
  35. data/spec/parser_spec.rb +380 -10
  36. data/spec/query_string_spec.rb +125 -0
  37. data/spec/request_errors_spec.rb +91 -0
  38. data/spec/request_spec.rb +28 -10
  39. data/spec/response_encoding_spec.rb +487 -0
  40. data/spec/url_filter_spec.rb +2 -1
  41. data/spec/url_spec.rb +37 -0
  42. metadata +10 -2
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 1a32c7da227fe7a2fbf3f106e6eb03af652694e293e4ea47928ee3adb71f21e5
4
- data.tar.gz: 6777d770a847f417cfa20a8cf70667e22db82393e2f6d5a839ac7d22406094ff
3
+ metadata.gz: 4b5d10a14ffef08c3fc9fd659e8b4ecdd5a5afab3b67f53cc553ce81f8ac3a2f
4
+ data.tar.gz: bb33246ce30dd3196176f56f4b94153d58dfd2e2c3459c70476579c8c9ef0db0
5
5
  SHA512:
6
- metadata.gz: 239049c807eaf8c178fe386be88b79fac5888934191f372ab3995fefe443026389e0b99d2f92f03e616eb93104acc24e6da15fa616da7172c2f067dc9da41aef
7
- data.tar.gz: 4676aaa3467c872f19db8b584eacf8cd66bfe9351adbe4f2fb882233043ba9aece759d93cb859f2aefaa41dca109becbaab25ca657bf66c6a37be6d7518b8606
6
+ metadata.gz: a6bc3242ca7ff77fa43b2038ea30a9e389bba55064bd948fbc31e640aa975aa6dc36b27297e9e5959d908a525c41159d629f3205c150ea4d5e19768818f63351
7
+ data.tar.gz: 1bb96d78211f2ed6e2b464c6e9eccf513a6bd42a4ba3be569a3954b1e1a879d067f0411b28cdd634b4bb3414254d8e3b5840f48e7ff02ee79ebbf4fa772d204e
data/CHANGELOG.md CHANGED
@@ -1,5 +1,42 @@
1
1
  # MetaInspector Changelog
2
2
 
3
+ ## [Changes in 6.0.0](https://github.com/jaimeiniesta/metainspector/compare/v5.22.0...v6.0.0)
4
+
5
+ * **Breaking:** `max_image_downloads` defaults to `20` instead of `nil` (unlimited), so a page with many images no longer decides how many requests `images.with_size`, `images.largest` and `images.best` make. Images past the limit that lack HTML dimensions get `[0, 0]` and can't win `largest`. Pass `max_image_downloads: nil` to keep downloading every image (#600).
6
+ * **Breaking:** raise `ArgumentError` for unknown options, naming them, instead of ignoring them. A misspelled option, or one with a String key as read from JSON or YAML, did nothing: `MetaInspector.new(url, 'document' => html)` fetched the page instead of parsing `html`. Option keys must be Symbols (#604).
7
+ * **Breaking:** `title` returns `nil` instead of `""` when the head has no `<title>` or it is blank, like `description`, `author` and the other readers, so `page.title || fallback` reaches the fallback. `title`, `description` and `best_description` trim surrounding whitespace, and `description` returns `nil` for a blank meta description; whitespace inside the text is kept as written. `to_hash['title']` and `to_hash['description']` change the same way (#604).
8
+ * **Breaking:** remove `page.feed` and `page.favicon`, which warn as deprecated since 5.21.0. Use `page.feeds` and `page.images.favicon` (#604).
9
+ * **Breaking:** remove the top-level `faraday_http_cache` option, deprecated in 5.20.0. Pass it inside `faraday_options`: `faraday_options: { faraday_http_cache: { store: cache } }`. The top-level option now raises `ArgumentError` (#604).
10
+ * **Breaking:** `images.with_size`, `images.largest` and `images.best` download one candidate per `<img>` or `<picture>` instead of every `srcset` candidate, which roughly tripled image downloads since 5.21.0. Each image is ranked by its largest candidate: the largest width descriptor if any, otherwise the highest density, with `src` as `1x`. A `src` with `width` and `height` in the HTML is still ranked without a download. **`with_size` changes**: it no longer lists the smaller candidates of each image. `to_a` and `with_details` still list every candidate (#600).
11
+
12
+ ## [Changes in 5.22.0](https://github.com/jaimeiniesta/metainspector/compare/v5.21.2...v5.22.0)
13
+
14
+ * `feeds` returns [JSON Feed 1.1](https://www.jsonfeed.org/version/1.1/) links (`application/feed+json`), and matches feed types case-insensitively and ignoring parameters, so `Application/Atom+XML` and `application/rss+xml; charset=utf-8` are found too. `type` keeps the attribute as written. The deprecated `feed` method still returns only RSS and Atom feeds, now also with parameters (#599).
15
+ * Raise `MetaInspector::TimeoutError` instead of `MetaInspector::RequestError` when connecting times out, and retry connection timeouts like read timeouts. **The error class changes**: if you rescue only `MetaInspector::RequestError`, rescue `MetaInspector::TimeoutError` too. Refused connections, DNS failures and other connection errors still raise `RequestError` and are not retried. The `connection_timeout + read_timeout + 1` deadline now applies to each attempt instead of the whole fetch, so `retries` gets all its attempts: before, `retries: 3` stopped after two or three. An attempt that reaches the deadline, such as one to a server that streams forever, is not retried, so it still raises `TimeoutError` after 41 seconds with the defaults. A page whose connection or read times out on every attempt now takes up to 4 × 40 seconds to fail, instead of 41 (#598).
16
+ * Raise `MetaInspector::RequestError` when a response is still compressed with an encoding MetaInspector doesn't decode, such as `br` or `zstd`, instead of parsing the compressed bytes as HTML and returning an empty page. Servers can send these even when asked for `Accept-Encoding: identity`. Adding the `brotli` gem enables `br` (#597).
17
+ * Replace invalid byte sequences in fetched pages with U+FFFD, as browsers do, instead of raising `MetaInspector::RequestError` when the charset comes from the `Content-Type` header. Before, they were only replaced with the `encoding:` option (#596).
18
+ * Resolve charset labels with the [Encoding Standard](https://encoding.spec.whatwg.org/#names-and-labels) table, as browsers do. Labels such as `ks_c_5601-1987`, `x-sjis`, `x-gbk` or `unicode-1-1-utf-8` no longer leave the page empty or garbled. `us-ascii` and `ascii` decode as Windows-1252 instead of raising `MetaInspector::RequestError`, and `iso-8859-9` and `iso-8859-11` as Windows-1254 and Windows-874. A UTF-16 label in a meta tag is read as UTF-8. A meta label that neither the table nor Ruby knows is ignored instead of cutting the document at the meta tag (#595).
19
+ * Return links inside inline `<svg>` and `<math>` again in `links`, as in 5.21.0. With the HTML5 parser those `<a>` elements are in another namespace, and the `//a/@href` lookup skipped them (#593).
20
+ * Return a page again for PDFs, binary files and deeply nested feeds with `allow_non_html_content: true`, instead of raising `MetaInspector::ParserError`. When the response is not `text/html`, parser resource limits no longer raise; if the HTML5 parser gives up, `parsed` falls back to the depth-capped HTML4 tree, as in 5.21.0. HTML responses and `max_html_bytes` are still enforced (#592).
21
+ * Fix `to_hash` raising `NoMethodError` on compressed responses. Header values that are not Strings, such as the Integer `Content-Length` set by faraday-gzip after decompressing, are kept as they are, and header names are downcased so `content-length` can be looked up as before (#591).
22
+ * Decode fetched UTF-16 and UTF-32 pages with a byte-order mark before removing NUL characters, even when the HTTP header has no charset. Preserve the raw response body and prefer the mark over conflicting meta declarations (#601).
23
+ * Preserve titles, head links and page content after tracking snippets in `<noscript>`, including unclosed or self-closing iframes. Parse each fallback separately so its links, images, stylesheets and iframes remain available (#602).
24
+ * Use the first meta charset declaration for binary HTML bodies, so a later conflicting declaration no longer garbles text or truncates the page. Preserve HTTP and string encodings, and prefer a byte-order mark over meta declarations (#575).
25
+ * Parse the DOM with HTML5 rules so paragraphs inside `h1`–`h6` retain their text, including the `best_title` heading fallback (#566). `parsed` now returns `Nokogiri::HTML5::Document`; malformed markup can produce a different tree, and literal CR/CRLF line endings in text and attributes normalize to LF. Preserve HTML4 encoding detection and text-size limits before HTML5 parsing, and wrap HTML5 depth-limit failures in `MetaInspector::ParserError`. Retain HTML4 parsing for legacy charsets that Ruby cannot transcode to UTF-8.
26
+ * Parse responses declared as UTF-16, UTF-32 or ISO-2022-JP by converting non-ASCII-compatible bodies to UTF-8 before removing NUL characters. Preserve the raw response body during conversion, replace invalid bytes with U+FFFD (#596) and wrap unsupported encoding conversions, such as UTF-7, in `MetaInspector::RequestError` (#568).
27
+ * Raise `MetaInspector::ParserError` during initialization when Nokogiri truncates HTML at its nesting or content resource limits, instead of silently returning incomplete links, headings and other metadata. Other recoverable HTML and encoding errors remain tolerated (#565). The nesting limit is the HTML5 parser's (400 levels), so pages that libxml2 truncated at 256 levels in 5.21.0 are now parsed in full. These include pages that only nest that deep in libxml2's HTML4 tree, such as unclosed `<div>`s inside `<section>`s; legacy charsets that Ruby cannot transcode keep the 256 limit. The 10 MB limit on text, attribute values and comments still applies past libxml2's nesting limit (#612).
28
+ * Convert response header values in `to_hash` to UTF-8, replacing invalid bytes, so non-ASCII headers no longer prevent JSON serialization. The original `response.headers` values are preserved (#563).
29
+ * Replace invalid byte sequences before parsing HTML passed with `document:`, so extracted text and `to_hash` no longer raise encoding errors. The original string returned by `to_s` is preserved (#569).
30
+ * Wrap malformed gzip/deflate responses and invalid `mailto:` page URLs or redirect destinations in `MetaInspector::RequestError`. Invalid `mailto:` image URLs return unknown dimensions instead of raising (#567).
31
+ * Return only the first `<title>` in the head for `title` and `to_hash['title']`, instead of concatenating all titles (#564).
32
+ * Fix `charset` returning `nil` for lowercase or mixed-case `http-equiv="content-type"` declarations. Read the `charset` parameter by name regardless of parameter order, spacing or case, and remove surrounding quotes (#562).
33
+ * Fix swapped `connection_timeout` and `read_timeout` options for GET and HEAD requests (#561). The connection timeout now limits opening the connection, and the read timeout limits waiting for the response.
34
+ * Fix garbled titles, descriptions and other text on compressed pages whose charset is declared only in the `Content-Type` header, including when custom headers enable compression (#572). Apply the charset after decompressing the response body.
35
+ * `untracked_url` and `untrack!` remove only the `utm_*` tracking parameters and keep the rest of the query string as written, instead of sorting keys, dropping repeated keys and re-encoding values (#557). **The returned URL changes** for any query with more than one parameter, or with `+` in a value: `?b=2&a=1` used to come back as `?a=1&b=2` and `?q=a+b` as `?q=a%20b`. If you store `untracked_url` values to spot duplicate pages, new results may not match the ones you saved before, so normalize both sides yourself or re-generate the stored values.
36
+ * Request page and image URLs with the query string as given, instead of sorting keys, keeping only the last value of a repeated key (`?tag=x&tag=y` was requested as `?tag=y`) and re-escaping values. URLs with non-UTF-8 escapes such as `?q=caf%E9` no longer raise `ArgumentError` (#594). **`url` changes too**: it reports the query that was requested, so, as with `untracked_url` above, stored values for queries with more than one parameter may not match new ones. With `normalize_url: true`, the default, normalization now escapes only what can't be sent (spaces, non-ASCII characters, `|`, `{`, `}`, a `%` that doesn't start an escape) and keeps reserved characters such as `;` and `[]` and existing escapes such as `%2F` or `%3D` as written, instead of escaping or decoding them (#613). **`links` and `head_links` change too** for queries with those characters, so stored link URLs may not match new ones either. Pass `normalize_url: false` to send the page URL unchanged.
37
+ * Fix `to_hash`, `content_type` and `response` raising `NoMethodError` when the HTML is passed with the `document` option. No request is made in that case, so `content_type` and `response` return `nil`, and `to_hash` includes `'content_type' => nil` and `'response' => nil` (#559).
38
+ * Fix `links`, `images`, `iframe_sources`, `head_links` and `feeds` taking quadratic time on pages with thousands of links, images, iframes or `<link>` elements. The whole document was searched for a `<base>` element once per element found; now it's searched once per page. Getting the links of a 700 KB page with 32,000 of them goes from 21 seconds to about 1, and results don't change (#573).
39
+
3
40
  ## [Changes in 5.21.2](https://github.com/jaimeiniesta/metainspector/compare/v5.21.1...v5.21.2)
4
41
 
5
42
  * Security: apply `max_html_bytes` while downloading page and redirect responses and during gzip/deflate decompression, before charset conversion and parsing. Oversized responses raise `MetaInspector::ParserError`; cached responses are checked as well. The 5.x default remains `nil` (unlimited); set a finite limit for untrusted URLs. Other content encodings are rejected with a finite limit ([GHSA-36j3-rh89-4gm2](https://github.com/jaimeiniesta/metainspector/security/advisories/GHSA-36j3-rh89-4gm2)).
data/README.md CHANGED
@@ -27,6 +27,40 @@ MetaInspector has been downloaded more than 4 million times via RubyGems.org and
27
27
 
28
28
  If you're using MetaInspector, please consider giving back to help ensure its continued development. You can support the project by becoming a sponsor on [GitHub Sponsors](https://github.com/sponsors/jaimeiniesta): pick the tier that suits you, either as an individual or on behalf of your company.
29
29
 
30
+ ### Gold Sponsors
31
+
32
+ <div style="display: flex; gap: 10px;">
33
+
34
+ <a href="https://github.com/sponsors/jaimeiniesta/sponsorships?sponsor=jaimeiniesta&tier_id=507665">
35
+ <img height="175" src="assets/sponsor_logo_placeholder.gif" alt="Become a Gold Sponsor">
36
+ </a>
37
+
38
+ </div>
39
+
40
+ ### Silver Sponsors
41
+
42
+ <div style="display: flex; gap: 10px;">
43
+
44
+ <a href="https://rocketvalidator.com">
45
+ <img height="150" src="assets/sponsor_logo_rocket_validator.png" alt="Rocket Validator - accessibility and HTML site-wide validator">
46
+ </a>
47
+
48
+ <a href="https://github.com/sponsors/jaimeiniesta/sponsorships?sponsor=jaimeiniesta&tier_id=63404">
49
+ <img height="150" src="assets/sponsor_logo_placeholder.gif" alt="Become a Silver Sponsor">
50
+ </a>
51
+
52
+ </div>
53
+
54
+ ### Bronze Sponsors
55
+
56
+ <div style="display: flex; gap: 10px;">
57
+
58
+ <a href="https://github.com/sponsors/jaimeiniesta/sponsorships?sponsor=jaimeiniesta&tier_id=63403">
59
+ <img height="125" src="assets/sponsor_logo_placeholder.gif" alt="Become a Bronze Sponsor">
60
+ </a>
61
+
62
+ </div>
63
+
30
64
  ## Usage
31
65
 
32
66
  Initialize a MetaInspector instance for an URL, like this:
@@ -48,6 +82,31 @@ page = MetaInspector.new("https://github.com",
48
82
  :document => "<html>...</html>")
49
83
  ```
50
84
 
85
+ ## Options reference
86
+
87
+ Pass these options as the second argument to `MetaInspector.new(url, options)`, with Symbol keys. Any other key, including a String key such as `'document'`, raises an `ArgumentError` that names it.
88
+
89
+ | Option | Default | Description |
90
+ | --- | --- | --- |
91
+ | `connection_timeout` | `20` | Maximum seconds to wait for a connection. |
92
+ | `read_timeout` | `20` | Maximum seconds to wait for a read once connected. |
93
+ | `retries` | `3` | Maximum additional attempts after a timeout. See [Timeout & Retries](#timeout--retries). |
94
+ | `allow_redirections` | `true` | Follow redirects, up to 10 by default; customize with `faraday_options[:redirect]`. |
95
+ | `head_first` | `false` | Check content type with HEAD before downloading with GET. |
96
+ | `document` | `nil` | HTML string to parse instead of fetching the page. |
97
+ | `headers` | User-Agent and Accept-Encoding | Request headers; a custom hash replaces the [default headers](#headers). |
98
+ | `encoding` | `nil` | Force the fetched body's encoding instead of relying on automatic detection. |
99
+ | `normalize_url` | `true` | Normalize URLs using Addressable. |
100
+ | `allow_non_html_content` | `false` | Allow non-HTML responses to be passed to the HTML parser. |
101
+ | `download_images` | `true` | Allow image downloads for dimensions, metadata and validation. |
102
+ | `max_image_downloads` | `20` | Limit image lookup attempts; `nil` for unlimited, `0` disables image downloads. |
103
+ | `download_image_options` | `nil` | Set `reject_invalid_images: true` in a hash to discard images that fail validation. |
104
+ | `fetch_all_image_meta` | `nil` (disabled) | Enable validity lookups through `images.with_metadata`. |
105
+ | `inline_image_data` | `nil` (disabled) | Return full data URLs and allow inline images in `best` and `largest`. |
106
+ | `max_html_bytes` | `nil` (unlimited) | Byte limit for each response body, decompression stage and processed HTML; exceeding it raises `ParserError`. See [Timeout & Retries](#timeout--retries). |
107
+ | `url_filter` | `nil` | Callable receiving a URI before each request; `false` or `nil` rejects the destination. |
108
+ | `faraday_options` | `nil` | Faraday configuration, including `redirect` and `faraday_http_cache` settings. |
109
+
51
110
  ## Accessing response
52
111
 
53
112
  You can check the status and headers from the response like this:
@@ -58,6 +117,10 @@ page.response.headers # { "server"=>"nginx", "content-type"=>"text/html; charset
58
117
  # "cache-control"=>"must-revalidate, private, max-age=0", ... }
59
118
  ```
60
119
 
120
+ When the HTML is passed with the `document` option, no request is made, so
121
+ `page.response` and `page.content_type` return `nil`, and so do the `response`
122
+ and `content_type` keys of `to_hash`.
123
+
61
124
  ## Accessing scraped data
62
125
 
63
126
  ### URL
@@ -78,24 +141,25 @@ page.root_url # Root url (scheme + host, like https://github.com/)
78
141
  page.head_links # an array of hashes of all head/links
79
142
  page.stylesheets # an array of hashes of all head/links where rel='stylesheet'
80
143
  page.canonicals # an array of hashes of all head/links where rel='canonical'
81
- page.feeds # Get rss or atom links in meta data fields as array of hash in the form { href: "...", title: "...", type: "..." }
144
+ page.feeds # RSS, Atom or JSON feed links as an array of hashes: { href: "...", title: "...", type: "..." }
82
145
  ```
83
146
 
84
- `page.feed` is a deprecated compatibility method that returns the first RSS or
85
- Atom feed's absolute URL, or `nil` if none is found. It skips JSON feeds. Each
86
- call emits a deprecation warning. Use `page.feeds` instead; `page.feed` is
87
- scheduled for removal in **6.0**.
147
+ `feeds` returns `<link rel="alternate">` elements whose `type` is
148
+ `application/rss+xml`, `application/atom+xml`, `application/feed+json` (JSON Feed
149
+ 1.1) or `application/json` (JSON Feed 1.0). The type is matched case-insensitively
150
+ and ignoring parameters such as `; charset=utf-8`; `type` in the result is the
151
+ attribute as written.
88
152
 
89
153
  ### Texts
90
154
 
91
155
  ```ruby
92
156
  page.language # declared language from the root <html lang="..."> attribute
93
- page.title # title of the page from the head section, as string
157
+ page.title # title of the page from the head section, or nil
94
158
  page.best_title # best title of the page, from a selection of candidates
95
159
  page.author # author of the page from the meta author tag
96
160
  page.best_author # best author of the page, from a selection of candidates
97
- page.description # returns the meta description
98
- page.best_description # returns the first non-empty description between the following candidates: standard meta description, og:description, twitter:description, the first long paragraph
161
+ page.description # returns the meta description, or nil
162
+ page.best_description # returns the first non-empty description between the following candidates: standard meta description, og:description, twitter:description, the first long paragraph; trims surrounding whitespace
99
163
  page.h1 # returns h1 text array
100
164
  page.h2 # returns h2 text array
101
165
  page.h3 # returns h3 text array
@@ -110,6 +174,10 @@ attribute is missing, empty, or whitespace-only. It does not infer language from
110
174
  the page content or other attributes. The value is also included in `to_hash`
111
175
  under the `"language"` key.
112
176
 
177
+ `title` is the text of the first `<title>` in the head and `description` the
178
+ content of the meta description. Both trim surrounding whitespace and return
179
+ `nil` when missing or blank, so `page.title || fallback` works.
180
+
113
181
  `best_title` selects the first non-empty value from the standard `title` meta tag,
114
182
  `og:title`, the head `<title>`, a body `<title>`, the first `<h1>`, and finally
115
183
  `parsely-title`.
@@ -135,21 +203,29 @@ page.links.external # every external link found on the page as an absolute
135
203
  page.images # enumerable collection of image URLs found on the page
136
204
  page.images.with_size # a sorted array (by descending area) of [image_url, width, height]
137
205
  page.images.with_details # image hashes with dimensions, type and file size (downloads images)
206
+ page.images.with_metadata # image hashes with URL and validity (enable lookups with fetch_all_image_meta: true)
207
+ page.images.largest # largest image, excluding aspect ratios of 10:1 or wider and 1:10 or taller
208
+ page.images.owner_suggested # first image from og:image, twitter:image, or parsely-image-url
138
209
  page.images.best # Most relevant image from og:image, twitter:image, or parsely-image-url; falls back to page.images.largest
139
210
  page.images.favicon # absolute URL to the favicon
140
211
  ```
141
212
 
142
- `page.favicon` is a deprecated shortcut for `page.images.favicon`, returning the
143
- same URL or `nil`. Each call emits a deprecation warning. Use
144
- `page.images.favicon` instead; `page.favicon` is scheduled for removal in **6.0**.
145
-
146
213
  The collection includes `img[src]`, `img[srcset]`, and `source[srcset]` inside
147
214
  `picture`, resolved to absolute URLs and deduplicated. Elements appear in document
148
215
  order; for each `img`, `src` comes before its `srcset` candidates, which retain
149
216
  their listed order. All candidates are included regardless of media conditions or
150
- device density. Responsive candidates use their downloaded dimensions for ranking;
151
- the `img` element's width and height apply only to its `src` fallback. By default,
152
- non-HTTP responsive URLs remain in the collection but cannot be downloaded for sizing.
217
+ device density. The `img` element's width and height apply only to its `src`
218
+ fallback. By default, non-HTTP responsive URLs remain in the collection but cannot
219
+ be downloaded for sizing.
220
+
221
+ `with_size`, `largest` and `best` treat the candidates of each `img` or `picture`
222
+ as one image at different sizes and rank only the largest one: the candidate with
223
+ the largest width descriptor (`800w`) if any has one, otherwise the highest density
224
+ (`2x`; `src` and candidates without a descriptor count as `1x`). That candidate is
225
+ downloaded for its dimensions, so each image costs at most one download. A `src`
226
+ with both `width` and `height` in the HTML is ranked as well, since it needs no
227
+ download. The other candidates are not in `with_size`; `to_a` and `with_details`
228
+ still list them all.
153
229
 
154
230
  `images.owner_suggested` tries `og:image`, `twitter:image`, and `parsely-image-url`
155
231
  in that order, skipping empty or whitespace-only values. Relative image URLs are
@@ -289,7 +365,7 @@ Please be aware that all keys are converted to downcase, so it's `'dc.date.issue
289
365
 
290
366
  ```ruby
291
367
  page.charset # UTF-8
292
- page.content_type # content-type returned by the server when the url was requested
368
+ page.content_type # content-type returned by the server when the url was requested, or nil with the document option
293
369
  ```
294
370
 
295
371
  ## Other representations
@@ -310,25 +386,52 @@ page.to_s # A String with the contents of the HTML document
310
386
  And the full scraped document is accessible from:
311
387
 
312
388
  ```ruby
313
- page.parsed # Nokogiri doc that you can use it to get any element from the page
389
+ page.parsed # Nokogiri::HTML5::Document that you can use to get any element from the page
314
390
  ```
315
391
 
392
+ The DOM follows HTML5 parsing rules, including keeping paragraphs inside headings
393
+ produced by CMS editors. Malformed markup may produce a different tree than the
394
+ previous HTML4 parser. HTML5 also normalizes literal CR and CRLF line endings to
395
+ LF, including in attribute values; `to_s` still returns the original document.
396
+ For legacy charsets that Ruby cannot convert to UTF-8 (such as UTF-7),
397
+ MetaInspector retains the HTML4 document and its parsing behavior.
398
+
316
399
  ## Options
317
400
 
318
401
  ### Forced encoding
319
402
 
320
- If you get a `MetaInspector::RequestError, "invalid byte sequence in UTF-8"` or similar error, you can try forcing the encoding like this:
403
+ Invalid byte sequences in the page's encoding are replaced with U+FFFD before
404
+ parsing, as browsers do, so one bad byte doesn't stop the rest of the page from
405
+ being read. If a page declares the wrong charset, you can force the right one:
321
406
 
322
407
  ```ruby
323
- page = MetaInspector.new(url, :encoding => 'UTF-8')
408
+ page = MetaInspector.new(url, :encoding => 'Windows-1252')
324
409
  ```
325
410
 
411
+ For HTML passed with `document:`, the original string is still available through `page.to_s`.
412
+
413
+ Legacy HTML charsets use browser-compatible supersets: GB2312 uses GBK,
414
+ Shift_JIS uses Windows-31J, EUC-KR uses CP949, Big5 uses Big5-HKSCS, and
415
+ ISO-8859-1 uses Windows-1252. This applies to HTTP charset declarations, HTML
416
+ meta declarations and the encoding of supplied strings, preserving characters
417
+ outside the strict legacy charset and the rest of the document. Declared meta
418
+ charsets and raw response bytes are preserved. Strings tagged with one of these
419
+ legacy encodings are converted to UTF-8 before cleanup; `page.to_s` returns the
420
+ converted text for downloaded pages.
421
+
422
+ Fetched bodies with non-ASCII-compatible encodings, such as UTF-16, UTF-32 and
423
+ ISO-2022-JP, are converted to UTF-8 before NUL characters are removed and the HTML
424
+ is parsed. `page.to_s` returns that UTF-8 text; the conversion preserves the raw
425
+ `page.response.body`. Invalid bytes are replaced with U+FFFD; conversions Ruby
426
+ doesn't support, such as UTF-7, raise `MetaInspector::RequestError` with the
427
+ original encoding error as the cause.
428
+
326
429
  ### Timeout & Retries
327
430
 
328
431
  You can specify 2 different timeouts when requesting a page:
329
432
 
330
433
  * `connection_timeout` sets the maximum number of seconds to wait to get a connection to the page.
331
- * `read_timeout` sets the maximum number of seconds to wait to read the page, once connected.
434
+ * `read_timeout` sets the maximum number of seconds to wait for a read, once connected.
332
435
 
333
436
  Both timeouts default to 20 seconds each.
334
437
 
@@ -339,7 +442,7 @@ documents, set `max_html_bytes` to a non-negative integer:
339
442
  page = MetaInspector.new(url, max_html_bytes: 2 * 1024 * 1024)
340
443
  ```
341
444
 
342
- The default in 5.x is `nil` (no limit). Set a finite limit when fetching URLs you
445
+ The default is `nil` (no limit). Set a finite limit when fetching URLs you
343
446
  do not control. Exceeding it raises `MetaInspector::ParserError` during
344
447
  initialization. The limit applies separately to the bytes received for each
345
448
  response (including redirect bodies), each stage of gzip/deflate decompression,
@@ -356,23 +459,43 @@ parsing deadline: even a small document can be
356
459
  slow to parse. Ruby's `Timeout.timeout` cannot reliably interrupt Nokogiri's
357
460
  native parser; use a separately supervised process if a hard deadline is needed.
358
461
 
359
- You can also specify the number of `retries`, which defaults to 3.
462
+ Nokogiri also enforces limits on nesting depth and the size of individual text
463
+ nodes, attribute values and comments. If one of these limits truncates the HTML,
464
+ MetaInspector raises `MetaInspector::ParserError` during initialization, with the
465
+ parser's diagnostic in the message. These limits apply even when `max_html_bytes`
466
+ is `nil`. MetaInspector retains an HTML4 pass for the size limits and encoding
467
+ detection before building the HTML5 DOM. The nesting limit is HTML5's, 400
468
+ levels; for legacy charsets that Ruby cannot transcode, where the HTML4 tree is
469
+ the DOM, it is HTML4's, 256 levels. Ordinary HTML errors and recoverable
470
+ encoding errors are still tolerated.
471
+
472
+ You can also specify the maximum number of additional attempts with `retries`,
473
+ which defaults to 3. Connection timeouts and read timeouts are retried. Other
474
+ connection failures, such as a refused connection or a DNS failure, are not.
475
+
476
+ Each attempt also has a deadline of `connection_timeout + read_timeout + 1`
477
+ seconds, which covers its redirects. It stops servers that keep sending data
478
+ slowly enough that the read timeout never fires. With the defaults, this is 41
479
+ seconds. An attempt that reaches the deadline is not retried, so such a server
480
+ holds the fetch for 41 seconds, not 41 for each retry. With `head_first: true`,
481
+ the HEAD and GET requests each get their own attempts.
360
482
 
361
- For example, this will time out after 10 seconds waiting for a connection, or after 5 seconds waiting
362
- to read its contents, and will retry 4 times:
483
+ For example, this allows up to 10 seconds to connect and 5 seconds per read, with
484
+ up to 4 additional attempts after a timeout, each within a 16-second deadline:
363
485
 
364
486
  ```ruby
365
- page = MetaInspector.new('www.google', :connection_timeout => 10, :read_timeout => 5, :retries => 4)
487
+ page = MetaInspector.new('https://example.com', connection_timeout: 10, read_timeout: 5, retries: 4)
366
488
  ```
367
489
 
368
- If MetaInspector fails to fetch the page after it has exhausted its retries,
369
- it will raise `MetaInspector::TimeoutError`, which you can rescue in your
370
- application code.
490
+ If the last attempt times out, or any attempt reaches the deadline, MetaInspector
491
+ raises `MetaInspector::TimeoutError`; other connection failures raise
492
+ `MetaInspector::RequestError`. Rescue both if your application handles them the
493
+ same way:
371
494
 
372
495
  ```ruby
373
496
  begin
374
497
  page = MetaInspector.new(url)
375
- rescue MetaInspector::TimeoutError
498
+ rescue MetaInspector::TimeoutError, MetaInspector::RequestError
376
499
  enqueue_for_future_fetch_attempt(url)
377
500
  render_simple(url)
378
501
  else
@@ -415,8 +538,8 @@ page = MetaInspector.new(url, faraday_options: { redirect: { callback: callback
415
538
  ```
416
539
 
417
540
 
418
- The `faraday_options[:redirect]` hash is passed to the `FollowRedirects` middleware used by `Faraday`, so that we can use all available options.
419
- Check them [here](https://github.com/lostisland/faraday_middleware/blob/main/lib/faraday_middleware/response/follow_redirects.rb#L44).
541
+ The `faraday_options[:redirect]` hash is passed to the `faraday-follow_redirects`
542
+ middleware. See its [available options](https://github.com/tisba/faraday-follow-redirects#usage).
420
543
  The origin header policy also applies after your redirect callback runs and when
421
544
  `clear_authorization_header: false` is set.
422
545
 
@@ -488,7 +611,13 @@ By default, the following headers are set:
488
611
  }
489
612
  ```
490
613
 
491
- The `Accept-Encoding` is set to `identity` to avoid exceptions being raised on servers that return malformed compressed responses, [as explained here](https://github.com/lostisland/faraday/issues/337).
614
+ `Accept-Encoding: identity` requests uncompressed responses to reduce problems with
615
+ malformed compressed data. Servers may still send compressed responses. gzip and
616
+ deflate are decoded, and malformed gzip or deflate data raises
617
+ `MetaInspector::RequestError`. Other encodings, such as `br` or `zstd`, also raise
618
+ `MetaInspector::RequestError` instead of being parsed as HTML. To decode `br`, add
619
+ the [`brotli`](https://rubygems.org/gems/brotli) gem to your Gemfile; this doesn't
620
+ apply with `max_html_bytes`, which only decodes gzip and deflate.
492
621
 
493
622
  If you want to override the default headers then use the `headers` option:
494
623
 
@@ -497,6 +626,10 @@ If you want to override the default headers then use the `headers` option:
497
626
  page = MetaInspector.new('example.com', :headers => {'User-Agent' => 'My custom User-Agent'})
498
627
  ```
499
628
 
629
+ The `headers` option replaces all default headers. To keep requesting uncompressed
630
+ responses with a custom User-Agent, also pass `'Accept-Encoding' => 'identity'`.
631
+ Otherwise, the compression middleware requests compressed responses automatically.
632
+
500
633
  ### Disabling SSL verification (or any other Faraday options)
501
634
 
502
635
  Faraday can be passed options via `:faraday_options`.
@@ -514,20 +647,24 @@ MetaInspector.new('https://example.com', faraday_options: { ssl: { verify: false
514
647
 
515
648
  ### Allow non-HTML content type
516
649
 
517
- MetaInspector will by default raise an exception when trying to parse a non-HTML URL (one that has a content-type different than text/html). You can disable this behaviour with:
650
+ MetaInspector fetches and parses the document during initialization. By default,
651
+ `MetaInspector.new` raises `MetaInspector::NonHtmlError` if the response declares a
652
+ content type other than `text/html`. You can disable this behaviour with:
518
653
 
519
654
  ```ruby
520
655
  page = MetaInspector.new('github.com', :allow_non_html_content => true)
521
656
  ```
522
657
 
523
658
  ```ruby
524
- page = MetaInspector.new('http://example.com/image.png')
525
- page.content_type # "image/png"
526
- page.description # will raise an exception
659
+ begin
660
+ page = MetaInspector.new('http://example.com/image.png')
661
+ rescue MetaInspector::NonHtmlError => error
662
+ warn error.message # The url provided contains image/png content instead of text/html content
663
+ end
527
664
 
528
665
  page = MetaInspector.new('http://example.com/image.png', :allow_non_html_content => true)
529
666
  page.content_type # "image/png"
530
- page.description # will return a garbled string
667
+ page.description # usually nil; non-HTML data is still passed to the HTML parser
531
668
  ```
532
669
 
533
670
  ### Check content type before downloading
@@ -557,15 +694,31 @@ redirect settings. Passing a `document` directly makes no HTTP requests.
557
694
  By default, URLs are normalized using the Addressable gem. For example:
558
695
 
559
696
  ```ruby
560
- # Normalization will add a default scheme and a trailing slash...
561
- page = MetaInspector.new('github.com')
562
- page.url # https://github.com/
697
+ # Normalization adds the default http scheme and a trailing slash.
698
+ # Supplying HTML avoids a request, so redirects cannot change the URL.
699
+ page = MetaInspector.new('example.com', document: '<html></html>')
700
+ page.url # http://example.com/
563
701
 
564
702
  # ...and it will also convert international characters
565
703
  page = MetaInspector.new('http://www.詹姆斯.com')
566
704
  page.url # http://www.xn--8ws00zhy3a.com/
567
705
  ```
568
706
 
707
+ When a page is fetched with redirects enabled, `page.url` is updated to the final
708
+ URL. For example, an HTTPS URL after requesting `github.com` reflects GitHub's
709
+ redirect from HTTP, rather than a default HTTPS scheme.
710
+
711
+ Normalization leaves the query string as written, except for characters that
712
+ can't be sent in a URL, such as spaces, non-ASCII characters, `|`, `{`, `}` or a
713
+ `%` that doesn't start an escape. Reserved characters such as `;` and `[]`, and
714
+ existing escapes such as `%2F`, are kept, because changing them can change the
715
+ page the server returns. The same applies to the URLs in `links` and `head_links`:
716
+
717
+ ```ruby
718
+ page = MetaInspector.new('http://example.com/?a[]=1;b=café')
719
+ page.url # http://example.com/?a[]=1;b=caf%C3%A9
720
+ ```
721
+
569
722
  While this is generally useful, it can be [tricky](https://github.com/sporkmonger/addressable/issues/182) [sometimes](https://github.com/sporkmonger/addressable/issues/160).
570
723
 
571
724
  You can disable URL normalization by passing the `normalize_url: false` option.
@@ -618,7 +771,7 @@ page = MetaInspector.new('http://example.com', max_image_downloads: 10)
618
771
  page.images.with_size
619
772
  ```
620
773
 
621
- The default is `nil` (unlimited). The option accepts a non-negative integer or `nil`; `0` disables image downloads. `download_images: false` always disables downloads, regardless of the limit.
774
+ The default is `20`; pass `nil` for no limit. The option accepts a non-negative integer or `nil`; `0` disables image downloads. `download_images: false` always disables downloads, regardless of the limit.
622
775
 
623
776
  By default, the limit counts image size lookup attempts in HTML order, after excluding unparseable URLs and duplicates. Images with both HTML dimensions already present do not consume the limit, and those dimensions are preserved even after the limit is reached. Failed lookups count toward the limit. Images with incomplete dimensions that are not downloaded remain in `images.with_size` with dimensions `[0, 0]`, matching the behavior when downloads are disabled.
624
777
 
@@ -674,26 +827,36 @@ Unsupported image URL schemes get `nil` metadata instead of raising; redirects t
674
827
 
675
828
  ### Caching responses
676
829
 
677
- MetaInspector can be configured to use [Faraday::HttpCache](https://github.com/plataformatec/faraday-http-cache) to cache page responses. For that you should pass the `faraday_http_cache` option inside `faraday_options`, with at least the `:store` key, for example:
830
+ MetaInspector can be configured to use [Faraday::HttpCache](https://github.com/sourcelevel/faraday-http-cache) to cache page responses. For that you should pass the `faraday_http_cache` option inside `faraday_options`, with at least the `:store` key, for example:
678
831
 
679
832
  ```ruby
680
833
  cache = ActiveSupport::Cache.lookup_store(:file_store, '/tmp/cache')
681
834
  page = MetaInspector.new('http://example.com', faraday_options: { faraday_http_cache: { store: cache } })
682
835
  ```
683
836
 
684
- The top-level `faraday_http_cache` option still works, but it is deprecated and prints a warning, once per process. Passing it in both places raises an `ArgumentError`.
837
+ The top-level `faraday_http_cache` option was removed in 6.0 and raises an `ArgumentError`.
685
838
 
686
839
  ## Exception Handling
687
840
 
688
841
  Web page scraping is tricky, you can expect to find different exceptions during the request of the page or the parsing of its contents. MetaInspector will encapsulate these exceptions on these main errors:
689
842
 
690
- * `MetaInspector::TimeoutError`. When fetching a web page has taken too long.
691
- * `MetaInspector::RequestError`. When there has been an error on the request phase. Examples: page not found, SSL failure, invalid URI.
843
+ * `MetaInspector::TimeoutError`. When connecting or reading times out and no retries are left, or an attempt reaches its deadline. See [Timeout & Retries](#timeout--retries).
844
+ * `MetaInspector::RequestError`. When there has been an error on the request phase. Examples: DNS failure, refused connection, SSL failure, invalid URI, malformed compressed response.
692
845
  * `MetaInspector::ParserError`. When there has been an error parsing the contents of the page.
693
846
  * `MetaInspector::NonHtmlError`. When the contents of the page was not HTML. See also the `allow_non_html_content` option
694
847
 
848
+ HTTP error statuses such as 403, 404 and 500 do not raise `MetaInspector::RequestError`. Their response bodies are processed like any other page, and you can check the status through `page.response.status`:
849
+
850
+ ```ruby
851
+ page = MetaInspector.new(url) # a URL that returns an HTML error page
852
+ page.response.status # => 404
853
+ page.title # => the title of the error page
854
+ ```
855
+
695
856
  ## Examples
696
857
 
858
+ For a web demo, see [metainspectordemo](https://github.com/jaimeiniesta/metainspectordemo): a small Rack app where you enter a URL and explore what MetaInspector extracts from it, including metadata, images, links, headings, feeds and the full `to_hash` output. Run it locally with `bundle exec rackup`.
859
+
697
860
  Runnable sample scripts live in `examples/`. From the repository root, pass the URL as an argument:
698
861
 
699
862
  ```sh
@@ -712,15 +875,19 @@ You can also run them from inside `examples/`, for example `bundle exec ruby bas
712
875
  * `iframes.rb`: lists iframe attributes and resolved source URLs without downloading embedded documents.
713
876
  * `html_size_limit.rb <url> [max_bytes]`: skips HTML over the byte limit (default: 2 MiB). The limit applies after download and does not bound parse time.
714
877
 
715
- What follows is an example of use from irb:
878
+ What follows is an example of use from irb. The `; nil` suppresses the document's
879
+ lengthy inspection output:
716
880
 
717
881
  ```ruby
718
882
  $ irb
719
883
  >> require 'metainspector'
720
884
  => true
721
885
 
722
- >> page = MetaInspector.new('http://github.com')
723
- => #<MetaInspector:0x11330c0 @url="http://github.com">
886
+ >> page = MetaInspector.new('http://github.com'); nil
887
+ => nil
888
+
889
+ >> page.class
890
+ => MetaInspector::Document
724
891
 
725
892
  >> page.title
726
893
  => "GitHub"
@@ -0,0 +1,40 @@
1
+ require 'timeout'
2
+ require 'net/http'
3
+ require 'faraday'
4
+
5
+ module MetaInspector
6
+ # Runs inside the retry middleware, so it applies to each attempt of a page
7
+ # request, redirects included, and every retry gets the full time.
8
+ class AttemptTimeout < Faraday::Middleware
9
+ # Not a Faraday::TimeoutError or Timeout::Error, so the retry middleware
10
+ # doesn't retry it. Request raises it as MetaInspector::TimeoutError.
11
+ class Expired < Faraday::Error; end
12
+
13
+ def initialize(app, seconds)
14
+ super(app)
15
+ @seconds = seconds
16
+ end
17
+
18
+ # Faraday's timeouts don't fire while a server keeps streaming, so each
19
+ # attempt also has its own deadline. An attempt that reaches it isn't
20
+ # retried: a server that keeps one busy that long would keep the next ones
21
+ # busy too.
22
+ #
23
+ # https://github.com/jaimeiniesta/metainspector/issues/188
24
+ # https://github.com/lostisland/faraday/issues/602
25
+ #
26
+ # The Net::HTTP adapter raises Faraday::ConnectionFailed for a connection
27
+ # timeout, as for a refused connection. Raising Faraday::TimeoutError instead
28
+ # lets the retry middleware retry it, and it reaches the caller as
29
+ # MetaInspector::TimeoutError (#598).
30
+ def call(env)
31
+ Timeout.timeout(@seconds) { @app.call(env) }
32
+ rescue Timeout::Error => error
33
+ raise Expired, error
34
+ rescue Faraday::ConnectionFailed => error
35
+ raise unless error.wrapped_exception.is_a?(Net::OpenTimeout)
36
+
37
+ raise Faraday::TimeoutError, error.wrapped_exception
38
+ end
39
+ end
40
+ end