use scraper::Selector;
pub fn parse_selector_with_fallback(selector_str: &str, context: &str) -> Selector {
Selector::parse(selector_str).unwrap_or_else(|e| {
log::error!(
"Failed to parse CSS selector '{selector_str}' in {context}: {e}. Using fallback selector."
);
Selector::parse("*:not(*)").expect(
"Fallback selector '*:not(*)' should always parse - this is a programming error",
)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_selector_with_fallback_valid() {
let selector = parse_selector_with_fallback("div", "test");
let html = scraper::Html::parse_fragment("<div>test</div>");
let matches: Vec<_> = html.select(&selector).collect();
assert_eq!(matches.len(), 1);
}
#[test]
fn test_parse_selector_with_fallback_invalid() {
let selector = parse_selector_with_fallback("div[invalid", "test");
let html = scraper::Html::parse_fragment("<div>test</div>");
let matches: Vec<_> = html.select(&selector).collect();
assert_eq!(matches.len(), 0);
}
#[test]
fn test_parse_selector_with_fallback_empty() {
let selector = parse_selector_with_fallback("", "test");
let html = scraper::Html::parse_fragment("<div>test</div>");
let matches: Vec<_> = html.select(&selector).collect();
assert_eq!(matches.len(), 0);
}
#[test]
fn test_parse_selector_with_fallback_complex_valid() {
let selector = parse_selector_with_fallback("div.container > p:first-child", "test");
let html =
scraper::Html::parse_fragment("<div class='container'><p>first</p><p>second</p></div>");
let matches: Vec<_> = html.select(&selector).collect();
assert_eq!(matches.len(), 1);
}
#[test]
fn test_parse_selector_with_fallback_malformed() {
let selector = parse_selector_with_fallback("div[attr='unclosed[", "test");
let html = scraper::Html::parse_fragment("<div attr='unclosed'>test</div>");
let matches: Vec<_> = html.select(&selector).collect();
assert_eq!(matches.len(), 0);
}
#[test]
fn test_parse_selector_with_fallback_special_characters() {
let selector = parse_selector_with_fallback("div#id.class[attr='value']", "test");
let html =
scraper::Html::parse_fragment("<div id='id' class='class' attr='value'>test</div>");
let matches: Vec<_> = html.select(&selector).collect();
assert_eq!(matches.len(), 1);
}
#[test]
fn test_parse_selector_with_fallback_pseudo_selectors() {
let selector = parse_selector_with_fallback("div:nth-child(2)", "test");
let html = scraper::Html::parse_fragment("<div>first</div><div>second</div>");
let matches: Vec<_> = html.select(&selector).collect();
assert_eq!(matches.len(), 1);
}
}