rvest:根据内部 class 文本过滤节点并计算内部 svg 元素的数量
rvest: Filter node based on inner class text and count number of svg elements inside
我的 HTML 看起来像:
<div class="rates">
<div class="rate">
<span class="title">A</span>
<img src="x.svg" alt="" width="20"><img src="x.svg" alt="" width="20"><img src="x.svg" alt="" width="20">
</div>
<div class="rate">
<span class="title">B</span>
<img src="y.svg" alt="" width="20"><img src="y.svg" alt="" width="20">
</div>
</div>
我想在 A
中获得 x.svg
的计数,在 B
中获得 y.svg
的计数。所以:
A: 3
B: 2
我有两个问题:
1. 如果我使用 html_nodes(".rate")
我会得到两者,但不知道如何根据标题文本进行过滤。
2. 计算 .svg
个元素出现的次数。
这是一种可能的解决方案,方法是找到所有父节点,然后计算每个父节点的 img 节点数。
library(rvest)
library(magrittr)
page<-read_html('<div class="rates">
<div class="rate">
<span class="title">A</span>
<img src="x.svg" alt="" width="20"><img src="x.svg" alt="" width="20"><img src="x.svg" alt="" width="20">
</div>
<div class="rate">
<span class="title">B</span>
<img src="y.svg" alt="" width="20"><img src="y.svg" alt="" width="20">
</div>
</div>')
#find all of the parent nodes
ratenodes <- page %>% html_nodes("div.rate")
#find a single title node per parent
titles <- ratenodes %>% html_node("span.title") %>% html_text()
#Count the number of img nodes per parent.
imagecount <- sapply(ratenodes, function(node) {
node %>% html_nodes("img") %>% length()})
answer<-data.frame(titles, imagecount)
我的 HTML 看起来像:
<div class="rates">
<div class="rate">
<span class="title">A</span>
<img src="x.svg" alt="" width="20"><img src="x.svg" alt="" width="20"><img src="x.svg" alt="" width="20">
</div>
<div class="rate">
<span class="title">B</span>
<img src="y.svg" alt="" width="20"><img src="y.svg" alt="" width="20">
</div>
</div>
我想在 A
中获得 x.svg
的计数,在 B
中获得 y.svg
的计数。所以:
A: 3
B: 2
我有两个问题:
1. 如果我使用 html_nodes(".rate")
我会得到两者,但不知道如何根据标题文本进行过滤。
2. 计算 .svg
个元素出现的次数。
这是一种可能的解决方案,方法是找到所有父节点,然后计算每个父节点的 img 节点数。
library(rvest)
library(magrittr)
page<-read_html('<div class="rates">
<div class="rate">
<span class="title">A</span>
<img src="x.svg" alt="" width="20"><img src="x.svg" alt="" width="20"><img src="x.svg" alt="" width="20">
</div>
<div class="rate">
<span class="title">B</span>
<img src="y.svg" alt="" width="20"><img src="y.svg" alt="" width="20">
</div>
</div>')
#find all of the parent nodes
ratenodes <- page %>% html_nodes("div.rate")
#find a single title node per parent
titles <- ratenodes %>% html_node("span.title") %>% html_text()
#Count the number of img nodes per parent.
imagecount <- sapply(ratenodes, function(node) {
node %>% html_nodes("img") %>% length()})
answer<-data.frame(titles, imagecount)