R:网络抓取不规则的值块
R: Webscraping irregular blocks of values
所以我正在尝试对一个网页进行网络抓取,该网页具有不规则的数据块,这些数据块的组织方式很容易用眼睛发现。假设我们正在查看维基百科。如果我从以下 link 的文章中抓取文本,我最终会得到 33 个条目。如果我只抓取 headers,我最终只有 7 个(见下面的代码)。这个结果并不让我们感到惊讶,因为我们知道文章的某些部分有多个段落,而其他部分只有一个段落文本或没有段落文本。
但我的问题是,如何将 header 与我的文本相关联。如果每个 header 或多个段落有相同数量的段落,这将是微不足道的。
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 节点,其中包含您想要的所有内容 children。
所以我正在尝试对一个网页进行网络抓取,该网页具有不规则的数据块,这些数据块的组织方式很容易用眼睛发现。假设我们正在查看维基百科。如果我从以下 link 的文章中抓取文本,我最终会得到 33 个条目。如果我只抓取 headers,我最终只有 7 个(见下面的代码)。这个结果并不让我们感到惊讶,因为我们知道文章的某些部分有多个段落,而其他部分只有一个段落文本或没有段落文本。
但我的问题是,如何将 header 与我的文本相关联。如果每个 header 或多个段落有相同数量的段落,这将是微不足道的。
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 节点,其中包含您想要的所有内容 children。