因此,我试图抓取一个网页,该网页包含不规则的数据 block ,这些数据 block 的组织方式很容易用眼睛发现。假设我们正在查看维基百科。如果我从以下链接的文章中抓取文本,我最终会得到 33 个条目。如果我只抓取标题,我最终只会得到 7 个标题(参见下面的代码)。这一结果并不让我们感到惊讶,因为我们知道文章的某些部分有多个段落,而其他部分只有一个段落文本或没有段落文本。
我的问题是,如何将标题与文本关联起来。如果每个标题有相同数量的段落或多个段落,这将是微不足道的。
library(rvest)
wiki <- html("https://en.wikipedia.org/wiki/Web_scraping")
wikitext <- wiki %>%
html_nodes('p+ ul li , p') %>%
html_text(trim=TRUE)
wikiheading <- wiki %>%
html_nodes('.mw-headline') %>%
html_text(trim=TRUE)
最佳答案
这将为您提供一个名为 content
的列表,其元素根据标题命名并包含相应的文本。
library(rvest) # Assumes version 0.2.0.9 is installed not currently on CRAN
wiki <- html("https://en.wikipedia.org/wiki/Web_scraping")
# This node set contains the headings and text
wikicontent <- wiki %>%
html_nodes("div[id='mw-content-text']") %>%
xml_children()
# Locates the positions of the headings
headings <- sapply(wikicontent,xml_name)
headings <- c(grep("h2",headings),length(headings)-1)
# Loop through the headings keeping the stuff in-between them as content
content <- list()
for (i in 1:(length(headings)-1)) {
foo <- wikicontent[headings[i]:(headings[i+1]-1)]
foo.title <- xml_text(foo[[1]])
foo.content <- xml_text(foo[-c(1)])
content[[i]] <- foo.content
names(content)[i] <- foo.title
}
关键是找到 mw-content-text 节点,它包含您想要作为子节点的所有内容。
关于R:网络抓取不规则的值 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31548571/