如何用R语言html_nodes匹配类名含desc-full的div元素?
Hey there! I see you're trying to pull content from elements where the class name shifts but always includes "desc-full" — let's get that sorted out for you.
Your initial attempt with .desc-full* throws an error because that's not how CSS selectors work. The * in that context isn't a wildcard for class names; instead, we need to use CSS attribute selectors or XPath to target elements whose class contains the substring we care about.
Solution 1: CSS Attribute Contains Selector
The most straightforward fix is using a CSS selector that matches elements where the class attribute contains the string "desc-full":
# Extract elements with class containing "desc-full" full_desc <- html_nodes(webpage, '[class*="desc-full"]') # Convert extracted nodes to plain text full_desc_text <- as.character(html_text(full_desc))
This selector [class*="desc-full"] will catch any element (div, p, etc.) where the class attribute has "desc-full" anywhere in its value — perfect for cases like desc-full, desc-full-v2, product-desc-full, etc.
If you want tighter precision:
- Use
[class^="desc-full"]to only match classes that start with "desc-full" - Use
[class$="desc-full"]to only match classes that end with "desc-full"
Solution 2: XPath Selector
If you prefer using XPath (fully supported by html_nodes), you can specifically target div elements with a class containing "desc-full" like this:
full_desc <- html_nodes(webpage, xpath = '//div[contains(@class, "desc-full")]') full_desc_text <- as.character(html_text(full_desc))
This is ideal if you want to restrict your selection to only div elements, avoiding other tags that might accidentally have the same class substring.
Why Your Original Code Failed
The .desc-full* syntax is invalid CSS — the * here would be interpreted as a universal selector (matching any element) that is a descendant of an element with class desc-full, which isn't what you intended. That's exactly why you got the Expected selector, got <DELIM '*' at 11> error.
内容的提问来源于stack exchange,提问作者Mark P.

