r - 使用 rvest 抓取 - 当标签不存在时使用 NAs 完成

标签 r tags web-scraping rvest

我想解析这个 HTML: 并从中获取这个元素:

a) p 标签,带有 class: "normal_encontrado"
b) divclass: "price"

有时,某些产品中不存在 p 标签。如果是这种情况,则应将 NA 添加到从该节点收集文本的向量中。

这个想法是有 2 个长度相同的向量,然后将它们连接起来形成 data.frame 。有任何想法吗?

HTML部分:

<html>
<head></head>
<body>

<div class="product_price" id="product_price_186251">
  <p class="normal_encontrado">
    S/. 2,799.00
  </p>

  <div id="WC_CatalogEntryDBThumbnailDisplayJSPF_10461_div_10" class="price">
    S/. 2,299.00
  </div>    
</div>

<div class="product_price" id="product_price_232046">
  <div id="WC_CatalogEntryDBThumbnailDisplayJSPF_10461_div_10" class="price">
    S/. 4,999.00
  </div>
</div>
</body>
</html>

代码:
library(rvest)

page_source <- read_html("r.html")

r.precio.antes <- page_source %>%
html_nodes(".normal_encontrado") %>%
html_text()

r.precio.actual <- page_source %>%
html_nodes(".price") %>%
html_text()

最佳答案

如果未找到该标签,则 rvest 返回一个字符 (0)。因此,假设您将在每个 div.product_price 中最多找到一个当前价格和一个常规价格,您可以使用以下命令:

pacman::p_load("rvest", "dplyr")

get_prices <- function(node){
  r.precio.antes <- html_nodes(node, 'p.normal_encontrado') %>% html_text
  r.precio.actual <- html_nodes(node, 'div.price') %>% html_text

  data.frame(
    precio.antes = ifelse(length(r.precio.antes)==0, NA, r.precio.antes),
    precio.actual = ifelse(length(r.precio.actual)==0, NA, r.precio.actual), 
    stringsAsFactors=F
  )

}

doc <- read_html('test.html') %>% html_nodes("div.product_price")
lapply(doc, get_prices) %>%
  rbind_all

编辑: 我误解了输入数据,因此将脚本更改为仅适用于单个 html 页面。

关于r - 使用 rvest 抓取 - 当标签不存在时使用 NAs 完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33250826/

相关文章:

r - 如何使用 rpy2 更改数据框的列名

azure - 在 Powershell 中创建 Azure API 管理标签

javascript - 需要有关 jQuery 插件的帮助 - TextExt 输入

java - 正则表达式查找文本中标签之间重复标签的单词

python - 使用 Beautifulsoup 进行抓取并出现错误 "Access to this page has been denied."

r - dplyr的`cummean()`函数未提供预期的结果

python - R 和 Python 的输出值不同?

通过评估反向引用来替换 gsub 中的文本

html - 如何使用 jquery 从 Rotten Tomatoes 检索搜索列表?

node.js - 如何将抓取内容放入 html(Node.js、cheerio)