使用rvest爬取网页时提取节点混入CSS代码的技术求助
解决rvest爬取时混入CSS样式文本的问题
你遇到的问题是因为目标网站采用了CSS-in-JS方案,样式规则被作为文本节点嵌入到DOM结构中,html_text()会提取目标节点下所有子节点的文本内容,自然包含了这些样式代码。不用gsub()的话,可以通过先移除无关节点再提取文本或者精准筛选目标文本节点来解决:
方法1:移除样式相关节点后提取文本
利用html_remove()先删掉所有带有css-前缀类的节点,再提取剩余内容的文本:
URL <- 'https://www.thepioneerwoman.com/food-cooking/recipes/a41138141/apple-pie-cookies-recipe/' recipe <- rvest::read_html(URL) directions <- recipe %>% rvest::html_nodes(".et3p2gv0") %>% # 移除所有class以css-开头的子元素 rvest::html_remove(rvest::html_nodes(., "[class^='css-']")) %>% rvest::html_text() %>% trimws()
方法2:用XPath精准筛选目标文本节点
直接通过XPath选择符合条件的文本节点,排除父元素是样式节点的文本:
URL <- 'https://www.thepioneerwoman.com/food-cooking/recipes/a41138141/apple-pie-cookies-recipe/' recipe <- rvest::read_html(URL) directions <- recipe %>% rvest::html_nodes(xpath = "//div[contains(@class, 'et3p2gv0')]//text()[not(parent::*[starts-with(@class, 'css-')])]") %>% paste(collapse = " ") %>% trimws()
这两种方法都能精准获取干净的步骤文本,避免了正则替换可能带来的误删问题。
内容的提问来源于stack exchange,提问作者Cole Baril
相关产品推荐
相关产品推荐

