R:网络抓取不规则的值 block

标签 r web-crawler rvest

因此,我试图抓取一个网页,该网页包含不规则的数据 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/

相关文章:

r - 迭代 R 中的模式 grep 函数

r - 合并列,按值对齐,当值不匹配时填充 NA

r - 访问函数的父环境并移除对象

python - Scrapy 只抓取网站的一部分

r - 使用 rvest 在 R 中进行 Web 抓取并找到 html_note

r - 如何在 rvest html_session 中发帖?

r - 如何组织大型 Shiny 应用程序?

java - 网络爬行一些网站并搜索其内容

java - 专门用于下载图像和文件的网络爬虫

python - 使用 R/Python 从 Web 下载数据的非 Selenium 方式