【问题标题】:How to exclude tags from scraping with rvest如何从 rvest 抓取中排除标签
【发布时间】:2020-02-25 14:45:12
【问题描述】:

我有以下 html 摘录:

<div class="price">
  <span class="float-right"><strong>1900</strong> USD</span>
</div>

我想检索金额和货币作为两个单独的变量。

对于金额,我可以通过以下代码毫无问题地得到它:

price <- rentalagency_html %>%
  rvest::html_nodes(css="div.price > span.float-right > strong") %>%
  rvest::html_text(trim=TRUE)
price

对于货币,我怎样才能只得到“美元”而没有金额?基本上,我想排除标签。

【问题讨论】:

  • 有网址可以分享吗?

标签: r rvest


【解决方案1】:

如果你读入整个 'span' 节点,你可以将生成的文本按空格分成两部分吗?

x <- '<div class="price">
  <span class="float-right"><strong>1900</strong> USD</span>
</div>'

x %>% 
  read_html() %>% 
  html_nodes(css='div.price > span') %>% 
  html_text(trim=TRUE) %>% 
  strsplit(' ')
[[1]]
[1] "1900" "USD" 

【讨论】:

  • 谢谢。只要您有价格和货币,它就可以工作。不幸的是,可能会发生没有价格的情况。如果我们可以在执行 html_nodes 时排除标记 strong 内的值,我会很好。这可能吗?
  • 你能给出没有价格的示例html吗?
  • 这里是一个例子:
    询价 NA
  • 或尝试使用 :not() 语法排除“强”。我不在机器旁,所以无法尝试,但请看这里:stackoverflow.com/questions/43038101/excluding-nodes-rvest
  • 我在发布我的问题之前实际上已经尝试过了。我无法让它工作。我的语法可能有问题:currency % rvest::html_nodes(css="div.price > span.float-right:not(strong)") %>% rvest::html_text(trim= TRUE) 货币
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-09
  • 2020-10-19
  • 1970-01-01
  • 2021-11-12
  • 1970-01-01
  • 2021-03-25
  • 1970-01-01
相关资源
最近更新 更多