返回 CodeWhale
scrape.rs
根目录 / crates / engine / src / tools / web / scrape.rs
1 //! Shared DuckDuckGo / Bing HTML SERP scrapers and spam filter.
2 //!
3 //! Used by both `web_search` and `web_run` so parser behavior (including the
4 //! #964 evidence-based spam filter) cannot drift between the two paths.
5
6 use base64::{Engine as _, engine::general_purpose};
7 use regex::Regex;
8 use std::sync::OnceLock;
9
10 /// Shared browser-like user agent for public SERP scraping and image search.
11 /// Both `web_search` and `web_run` send this so scrape behavior (including
12 /// bot-challenge rates) stays identical between the two surfaces.
13 pub const BROWSER_USER_AGENT: &str = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15";
14
15 /// One parsed search hit: title, absolute URL, optional snippet.
16 #[derive(Debug, Clone, PartialEq, Eq)]
17 pub struct ScrapedSearchResult {
18 pub title: String,
19 pub url: String,
20 pub snippet: Option<String>,
21 }
22
23 // Cached regex patterns for HTML parsing
24 static TITLE_RE: OnceLock<Regex> = OnceLock::new();
25 static SNIPPET_RE: OnceLock<Regex> = OnceLock::new();
26 static TAG_RE: OnceLock<Regex> = OnceLock::new();
27 static BING_RESULT_RE: OnceLock<Regex> = OnceLock::new();
28 static BING_TITLE_RE: OnceLock<Regex> = OnceLock::new();
29 static BING_SNIPPET_RE: OnceLock<Regex> = OnceLock::new();
30
31 fn get_title_re() -> &'static Regex {
32 TITLE_RE.get_or_init(|| {
33 Regex::new(r#"<a[^>]*class=\"result__a\"[^>]*href=\"([^\"]+)\"[^>]*>(.*?)</a>"#)
34 .expect("title regex pattern is valid")
35 })
36 }
37
38 fn get_snippet_re() -> &'static Regex {
39 SNIPPET_RE.get_or_init(|| {
40 Regex::new(
41 r#"<a[^>]*class=\"result__snippet\"[^>]*>(.*?)</a>|<div[^>]*class=\"result__snippet\"[^>]*>(.*?)</div>"#,
42 )
43 .expect("snippet regex pattern is valid")
44 })
45 }
46
47 fn get_tag_re() -> &'static Regex {
48 TAG_RE.get_or_init(|| Regex::new(r"<[^>]+>").expect("tag regex pattern is valid"))
49 }
50
51 fn get_bing_result_re() -> &'static Regex {
52 BING_RESULT_RE.get_or_init(|| {
53 Regex::new(r#"(?is)<li[^>]*class=\"[^\"]*\bb_algo\b[^\"]*\"[^>]*>(.*?)</li>"#)
54 .expect("bing result regex pattern is valid")
55 })
56 }
57
58 fn get_bing_title_re() -> &'static Regex {
59 BING_TITLE_RE.get_or_init(|| {
60 Regex::new(r#"(?is)<h2[^>]*>.*?<a[^>]*href=\"([^\"]+)\"[^>]*>(.*?)</a>"#)
61 .expect("bing title regex pattern is valid")
62 })
63 }
64
65 fn get_bing_snippet_re() -> &'static Regex {
66 BING_SNIPPET_RE.get_or_init(|| {
67 Regex::new(r#"(?is)<div[^>]*class=\"[^\"]*\bb_caption\b[^\"]*\"[^>]*>.*?<p[^>]*>(.*?)</p>"#)
68 .expect("bing snippet regex pattern is valid")
69 })
70 }
71
72 /// Parse DuckDuckGo HTML SERP results. Known spam-domain hits are omitted.
73 pub fn parse_duckduckgo_results(html: &str, max_results: usize) -> Vec<ScrapedSearchResult> {
74 let title_re = get_title_re();
75 let snippet_re = get_snippet_re();
76 let title_caps: Vec<_> = title_re.captures_iter(html).collect();
77
78 let mut results = Vec::new();
79 for (idx, cap) in title_caps.iter().enumerate() {
80 if results.len() >= max_results {
81 break;
82 }
83 let Some(full_match) = cap.get(0) else {
84 continue;
85 };
86 let href = cap.get(1).map(|m| m.as_str()).unwrap_or("");
87 let title_raw = cap.get(2).map(|m| m.as_str()).unwrap_or("");
88 let title = normalize_text(title_raw);
89 if title.is_empty() {
90 continue;
91 }
92 let url = normalize_duckduckgo_url(href);
93 if is_known_spam_url(&url) {
94 continue;
95 }
96 let span_end = title_caps
97 .get(idx + 1)
98 .and_then(|next| next.get(0))
99 .map_or(html.len(), |m| m.start());
100 let span = &html[full_match.end()..span_end];
101 let snippet = snippet_re
102 .captures(span)
103 .and_then(|snippet_cap| snippet_cap.get(1).or_else(|| snippet_cap.get(2)))
104 .map(|m| normalize_text(m.as_str()))
105 .filter(|s| !s.is_empty());
106
107 results.push(ScrapedSearchResult {
108 title,
109 url,
110 snippet,
111 });
112 }
113
114 results
115 }
116
117 /// Parse Bing HTML SERP results. Known spam-domain hits are omitted.
118 pub fn parse_bing_results(html: &str, max_results: usize) -> Vec<ScrapedSearchResult> {
119 let mut results = Vec::new();
120 for cap in get_bing_result_re().captures_iter(html) {
121 if results.len() >= max_results {
122 break;
123 }
124 let Some(block) = cap.get(1).map(|m| m.as_str()) else {
125 continue;
126 };
127 let Some(title_cap) = get_bing_title_re().captures(block) else {
128 continue;
129 };
130 let href = title_cap.get(1).map(|m| m.as_str()).unwrap_or("");
131 let title_raw = title_cap.get(2).map(|m| m.as_str()).unwrap_or("");
132 let title = normalize_text(title_raw);
133 if title.is_empty() {
134 continue;
135 }
136 let snippet = get_bing_snippet_re()
137 .captures(block)
138 .and_then(|snippet_cap| snippet_cap.get(1))
139 .map(|m| normalize_text(m.as_str()))
140 .filter(|s| !s.is_empty());
141
142 let url = normalize_bing_url(href);
143 if is_known_spam_url(&url) {
144 continue;
145 }
146 results.push(ScrapedSearchResult {
147 title,
148 url,
149 snippet,
150 });
151 }
152 results
153 }
154
155 /// Detect DuckDuckGo bot-challenge interstitial HTML.
156 pub fn is_duckduckgo_challenge(html: &str) -> bool {
157 html.contains("anomaly-modal") || html.contains("Unfortunately, bots use DuckDuckGo too")
158 }
159
160 /// Evidence-based filter for the domain family in #964. A broad same-domain
161 /// ratio is not a spam signal: site-scoped searches and documentation hosts
162 /// legitimately return many results from one registrable domain.
163 fn is_known_spam_url(url: &str) -> bool {
164 const KNOWN_SPAM_DOMAINS: &[&str] = &["forumgratuit.org"];
165
166 let Ok(parsed) = reqwest::Url::parse(url) else {
167 return false;
168 };
169 let Some(host) = parsed.host_str() else {
170 return false;
171 };
172 KNOWN_SPAM_DOMAINS
173 .iter()
174 .any(|domain| host == *domain || host.ends_with(&format!(".{domain}")))
175 }
176
177 fn normalize_duckduckgo_url(href: &str) -> String {
178 let href = decode_html_entities(href);
179 let href = href.as_str();
180 if let Some(uddg) = extract_query_param(href, "uddg") {
181 let decoded = percent_decode(&uddg);
182 if !decoded.is_empty() {
183 return decoded;
184 }
185 }
186 if href.starts_with("//") {
187 return format!("https:{href}");
188 }
189 if href.starts_with('/') {
190 return format!("https://duckduckgo.com{href}");
191 }
192 href.to_string()
193 }
194
195 /// Normalize a Bing SERP result href, unwrapping `/ck/a?...&u=<base64>` redirects.
196 pub fn normalize_bing_url(href: &str) -> String {
197 // Bing wraps every SERP result URL in a `/ck/a?...&u=<base64>` click-tracking
198 // redirect, and in the raw HTML the separators are `&amp;` entities. Without
199 // decoding entities first, `extract_query_param` looks for `u` but the actual
200 // key is `amp;u`, so the real URL is never recovered and callers receive Bing's
201 // tracking URL instead of the cited source. Decode entities before parsing.
202 let href = decode_html_entities(href);
203 let href = href.as_str();
204 if let Some(encoded) = extract_query_param(href, "u") {
205 let decoded = percent_decode(&encoded);
206 let token = decoded.strip_prefix("a1").unwrap_or(&decoded);
207 let mut padded = token.replace('-', "+").replace('_', "/");
208 while !padded.len().is_multiple_of(4) {
209 padded.push('=');
210 }
211 if let Ok(bytes) = general_purpose::STANDARD.decode(padded)
212 && let Ok(url) = String::from_utf8(bytes)
213 && (url.starts_with("http://") || url.starts_with("https://"))
214 {
215 return url;
216 }
217 }
218 if href.starts_with("//") {
219 return format!("https:{href}");
220 }
221 if href.starts_with('/') {
222 return format!("https://www.bing.com{href}");
223 }
224 href.to_string()
225 }
226
227 fn normalize_text(text: &str) -> String {
228 let stripped = strip_html_tags(text);
229 let decoded = decode_html_entities(&stripped);
230 decoded.split_whitespace().collect::<Vec<_>>().join(" ")
231 }
232
233 fn strip_html_tags(text: &str) -> String {
234 get_tag_re().replace_all(text, "").to_string()
235 }
236
237 /// Decode common HTML named and numeric character references.
238 pub fn decode_html_entities(text: &str) -> String {
239 static ENTITY_RE: OnceLock<Regex> = OnceLock::new();
240 let re = ENTITY_RE.get_or_init(|| {
241 Regex::new(r"&(?:#(\d+)|#x([0-9A-Fa-f]+)|([a-zA-Z]+));").expect("HTML entity regex")
242 });
243
244 re.replace_all(text, |caps: &regex::Captures| {
245 if let Some(dec) = caps.get(1) {
246 return dec
247 .as_str()
248 .parse::<u32>()
249 .ok()
250 .and_then(std::char::from_u32)
251 .unwrap_or('\u{FFFD}')
252 .to_string();
253 }
254 if let Some(hex) = caps.get(2) {
255 return u32::from_str_radix(hex.as_str(), 16)
256 .ok()
257 .and_then(std::char::from_u32)
258 .unwrap_or('\u{FFFD}')
259 .to_string();
260 }
261 let named = caps.get(3).map(|m| m.as_str());
262 match named {
263 Some("amp") => "&",
264 Some("lt") => "<",
265 Some("gt") => ">",
266 Some("quot") => "\"",
267 Some("apos") => "'",
268 Some("nbsp") => " ",
269 Some("copy") => "\u{00A9}",
270 Some("reg") => "\u{00AE}",
271 Some("mdash") => "\u{2014}",
272 Some("ndash") => "\u{2013}",
273 Some("lsquo") => "\u{2018}",
274 Some("rsquo") => "\u{2019}",
275 Some("ldquo") => "\u{201C}",
276 Some("rdquo") => "\u{201D}",
277 Some("hellip") => "\u{2026}",
278 _ => return caps.get(0).map(|m| m.as_str()).unwrap_or("").to_string(),
279 }
280 .to_string()
281 })
282 .to_string()
283 }
284
285 /// Percent-decode a URL component. `+` becomes space (query-string convention).
286 pub fn percent_decode(input: &str) -> String {
287 let bytes = input.as_bytes();
288 let mut out = Vec::new();
289 let mut i = 0;
290 while i < bytes.len() {
291 match bytes[i] {
292 b'%' if i + 2 < bytes.len() => {
293 if let (Some(hi), Some(lo)) = (hex_nibble(bytes[i + 1]), hex_nibble(bytes[i + 2])) {
294 out.push((hi << 4) | lo);
295 i += 3;
296 continue;
297 }
298 out.push(bytes[i]);
299 }
300 b'+' => out.push(b' '),
301 _ => out.push(bytes[i]),
302 }
303 i += 1;
304 }
305 String::from_utf8_lossy(&out).to_string()
306 }
307
308 fn hex_nibble(byte: u8) -> Option<u8> {
309 match byte {
310 b'0'..=b'9' => Some(byte - b'0'),
311 b'a'..=b'f' => Some(byte - b'a' + 10),
312 b'A'..=b'F' => Some(byte - b'A' + 10),
313 _ => None,
314 }
315 }
316
317 fn extract_query_param(url: &str, key: &str) -> Option<String> {
318 let query = url.split_once('?')?.1;
319 for part in query.split('&') {
320 let mut iter = part.splitn(2, '=');
321 let name = iter.next().unwrap_or("");
322 if name == key {
323 return iter.next().map(str::to_string);
324 }
325 }
326 None
327 }
328
329 #[cfg(test)]
330 mod tests {
331 use super::*;
332
333 #[test]
334 fn duckduckgo_pairs_snippets_within_each_result_span() {
335 let html = r#"
336 <a class="result__snippet">Stray leading snippet</a>
337 <a class="result__a" href="https://one.example/">One</a>
338 <a class="result__a" href="https://two.example/">Two</a>
339 <a class="result__snippet">Snippet that belongs to two</a>
340 <div class="result__snippet">Extra snippet inside two</div>
341 "#;
342 let results = parse_duckduckgo_results(html, 5);
343 assert_eq!(results.len(), 2);
344 assert_eq!(results[0].title, "One");
345 assert_eq!(results[0].snippet, None);
346 assert_eq!(results[1].title, "Two");
347 assert_eq!(
348 results[1].snippet.as_deref(),
349 Some("Snippet that belongs to two")
350 );
351 }
352
353 #[test]
354 fn duckduckgo_uddg_redirect_decodes_html_entities() {
355 let html = r#"
356 <a class="result__a" href="//duckduckgo.com/l/?kh=-1&amp;uddg=https%3A%2F%2Fexample.com%2Fdocs%3Fa%3D1%26b%3D2">Docs</a>
357 <a class="result__snippet">Reference docs</a>
358 "#;
359 let results = parse_duckduckgo_results(html, 5);
360 assert_eq!(results.len(), 1);
361 assert_eq!(results[0].url, "https://example.com/docs?a=1&b=2");
362 assert_eq!(results[0].snippet.as_deref(), Some("Reference docs"));
363 }
364
365 #[test]
366 fn percent_decode_does_not_panic_on_multibyte_after_percent() {
367 assert_eq!(percent_decode("%中文"), "%中文");
368 assert_eq!(percent_decode("%aé"), "%aé");
369 assert_eq!(percent_decode("100%中%20ok"), "100%中 ok");
370 }
371
372 // Regression guard: Bing /ck/a redirect hrefs are HTML-entity-encoded
373 // (`&amp;`). normalize_bing_url must decode entities before extracting the
374 // `u=` base64 payload, otherwise the real URL is never recovered and the
375 // result remains a Bing tracking URL instead of the cited source.
376 #[test]
377 fn bing_ckurl_with_html_entities_decodes_real_url() {
378 let href = "https://www.bing.com/ck/a?!&amp;&amp;p=abc&amp;u=a1aHR0cHM6Ly9ydXN0LWxhbmcub3JnLw&amp;ntb=1";
379 assert_eq!(normalize_bing_url(href), "https://rust-lang.org/");
380 }
381
382 #[test]
383 fn parses_bing_results_and_decodes_redirect_url() {
384 let html = r#"
385 <ol>
386 <li class="b_algo">
387 <h2><a href="https://www.bing.com/ck/a?u=a1aHR0cHM6Ly9leGFtcGxlLmNvbS9wYXRoP3E9MQ">Example &amp; Result</a></h2>
388 <div class="b_caption"><p>A <strong>useful</strong> snippet.</p></div>
389 </li>
390 </ol>
391 "#;
392
393 let results = parse_bing_results(html, 5);
394
395 assert_eq!(results.len(), 1);
396 assert_eq!(results[0].title, "Example & Result");
397 assert_eq!(results[0].url, "https://example.com/path?q=1");
398 assert_eq!(results[0].snippet.as_deref(), Some("A useful snippet."));
399 }
400
401 #[test]
402 fn parses_duckduckgo_results() {
403 let html = r#"
404 <a class="result__a" href="https://example.com/rust">Rust &amp; async</a>
405 <a class="result__snippet">A <b>useful</b> snippet.</a>
406 <a class="result__a" href="//docs.rs/tokio">Tokio</a>
407 <div class="result__snippet">Runtime docs</div>
408 "#;
409 let results = parse_duckduckgo_results(html, 5);
410 assert_eq!(results.len(), 2);
411 assert_eq!(results[0].title, "Rust & async");
412 assert_eq!(results[0].url, "https://example.com/rust");
413 assert_eq!(results[0].snippet.as_deref(), Some("A useful snippet."));
414 assert_eq!(results[1].url, "https://docs.rs/tokio");
415 }
416
417 #[test]
418 fn known_spam_filter_is_domain_specific() {
419 assert!(is_known_spam_url("https://astralia.forumgratuit.org/page1"));
420 assert!(!is_known_spam_url("https://forumgratuit.org.example/a"));
421 assert!(!is_known_spam_url("https://docs.example.com/a"));
422 }
423
424 #[test]
425 fn legitimate_same_domain_results_are_preserved() {
426 let html = r#"
427 <a class="result__a" href="https://docs.example.com/a">A</a>
428 <a class="result__snippet">s</a>
429 <a class="result__a" href="https://docs.example.com/b">B</a>
430 <a class="result__snippet">s</a>
431 <a class="result__a" href="https://docs.example.com/c">C</a>
432 <a class="result__snippet">s</a>
433 <a class="result__a" href="https://docs.example.com/d">D</a>
434 <a class="result__snippet">s</a>
435 "#;
436 assert_eq!(parse_duckduckgo_results(html, 10).len(), 4);
437 }
438
439 #[test]
440 fn public_suffix_and_private_suffix_hosts_are_not_misgrouped() {
441 let html = r#"
442 <a class="result__a" href="https://alpha.example.co.uk/a">A</a>
443 <a class="result__snippet">s</a>
444 <a class="result__a" href="https://beta.example.co.uk/b">B</a>
445 <a class="result__snippet">s</a>
446 <a class="result__a" href="https://alice.github.io/c">C</a>
447 <a class="result__snippet">s</a>
448 <a class="result__a" href="https://bob.github.io/d">D</a>
449 <a class="result__snippet">s</a>
450 "#;
451 assert_eq!(parse_duckduckgo_results(html, 10).len(), 4);
452 }
453
454 #[test]
455 fn max_results_three_keeps_legitimate_same_domain_results() {
456 let html = r#"
457 <a class="result__a" href="https://docs.example.com/a">A</a>
458 <a class="result__snippet">s</a>
459 <a class="result__a" href="https://docs.example.com/b">B</a>
460 <a class="result__snippet">s</a>
461 <a class="result__a" href="https://docs.example.com/c">C</a>
462 <a class="result__snippet">s</a>
463 <a class="result__a" href="https://docs.example.com/d">D</a>
464 <a class="result__snippet">s</a>
465 "#;
466 assert_eq!(parse_duckduckgo_results(html, 3).len(), 3);
467 }
468
469 #[test]
470 fn parse_duckduckgo_filters_known_spam_domain() {
471 // Shared path used by web_run and web_search: known spam → empty.
472 let html = r#"
473 <a class="result__a" href="https://astralia.forumgratuit.org/a">A</a>
474 <a class="result__snippet">s</a>
475 <a class="result__a" href="https://russia.forumgratuit.org/b">B</a>
476 <a class="result__snippet">s</a>
477 <a class="result__a" href="https://other.forumgratuit.org/c">C</a>
478 <a class="result__snippet">s</a>
479 <a class="result__a" href="https://hello.forumgratuit.org/d">D</a>
480 <a class="result__snippet">s</a>
481 <a class="result__a" href="https://world.forumgratuit.org/e">E</a>
482 <a class="result__snippet">s</a>
483 "#;
484 assert!(parse_duckduckgo_results(html, 10).is_empty());
485 }
486
487 #[test]
488 fn parse_bing_filters_known_spam_domain() {
489 let html = r#"
490 <ol>
491 <li class="b_algo">
492 <h2><a href="https://astralia.forumgratuit.org/a">A</a></h2>
493 <div class="b_caption"><p>s</p></div>
494 </li>
495 <li class="b_algo">
496 <h2><a href="https://russia.forumgratuit.org/b">B</a></h2>
497 <div class="b_caption"><p>s</p></div>
498 </li>
499 <li class="b_algo">
500 <h2><a href="https://other.forumgratuit.org/c">C</a></h2>
501 <div class="b_caption"><p>s</p></div>
502 </li>
503 <li class="b_algo">
504 <h2><a href="https://hello.forumgratuit.org/d">D</a></h2>
505 <div class="b_caption"><p>s</p></div>
506 </li>
507 <li class="b_algo">
508 <h2><a href="https://world.forumgratuit.org/e">E</a></h2>
509 <div class="b_caption"><p>s</p></div>
510 </li>
511 </ol>
512 "#;
513 assert!(parse_bing_results(html, 10).is_empty());
514 }
515
516 #[test]
517 fn decode_html_entities_handles_named_entities() {
518 assert_eq!(decode_html_entities("&amp;"), "&");
519 assert_eq!(decode_html_entities("&lt;"), "<");
520 assert_eq!(decode_html_entities("&gt;"), ">");
521 assert_eq!(decode_html_entities("&quot;"), "\"");
522 assert_eq!(decode_html_entities("&apos;"), "'");
523 assert_eq!(decode_html_entities("&nbsp;"), " ");
524 assert_eq!(decode_html_entities("&copy;"), "\u{00A9}");
525 assert_eq!(decode_html_entities("&mdash;"), "\u{2014}");
526 }
527
528 #[test]
529 fn decode_html_entities_handles_decimal_numeric_references() {
530 assert_eq!(decode_html_entities("&#65;"), "A");
531 assert_eq!(decode_html_entities("&#60;"), "<");
532 assert_eq!(decode_html_entities("&#8211;"), "\u{2013}");
533 }
534
535 #[test]
536 fn decode_html_entities_handles_hex_numeric_references() {
537 assert_eq!(decode_html_entities("&#x41;"), "A");
538 assert_eq!(decode_html_entities("&#x3C;"), "<");
539 assert_eq!(decode_html_entities("&#x2014;"), "\u{2014}");
540 }
541
542 #[test]
543 fn decode_html_entities_passthrough_unknown() {
544 assert_eq!(decode_html_entities("&unknown;"), "&unknown;");
545 }
546
547 #[test]
548 fn decode_html_entities_mixed_content() {
549 let input = "Hello &amp; welcome to &quot;Rust&apos;s world&quot; &mdash; enjoy!";
550 let expected = "Hello & welcome to \"Rust's world\" \u{2014} enjoy!";
551 assert_eq!(decode_html_entities(input), expected);
552 }
553
554 #[test]
555 fn percent_decode_handles_utf8_multibyte_sequences() {
556 // Percent-encoded CJK: %E4%B8%AA%E4%BA%BA = 个人 (each glyph is 3 UTF-8 bytes).
557 assert_eq!(percent_decode("Hello %E4%B8%AA%E4%BA%BA"), "Hello 个人");
558 assert_eq!(percent_decode("%E7%B4%A0%E6%9D%90"), "素材");
559 // Percent-encoded UTF-8 inside a URL path (DuckDuckGo `uddg=` redirect shape).
560 assert_eq!(
561 percent_decode("https://example.com/%E9%A1%B5%E9%9D%A2"),
562 "https://example.com/页面"
563 );
564 // Raw UTF-8 in the input passes through unchanged.
565 assert_eq!(percent_decode("查询 keyword"), "查询 keyword");
566 // Query-string convention: `+` becomes space; `%20` becomes space.
567 assert_eq!(percent_decode("foo+bar%20baz"), "foo bar baz");
568 }
569
570 #[test]
571 fn is_duckduckgo_challenge_detects_interstitial() {
572 assert!(is_duckduckgo_challenge(
573 "Unfortunately, bots use DuckDuckGo too."
574 ));
575 assert!(is_duckduckgo_challenge(
576 r#"<div class="anomaly-modal">challenge</div>"#
577 ));
578 assert!(!is_duckduckgo_challenge(
579 r#"<a class="result__a" href="https://example.com">ok</a>"#
580 ));
581 }
582 }
583
583 lines RUST