【问题标题】:rvest table scraping including linksrvest 表抓取,包括链接
【发布时间】:2015-11-02 15:53:12
【问题描述】:

我想从 Wikipedia 上抓取一些表格数据。一些表格列包含指向我想保留的其他文章的链接。我试过this approach,它没有保留 URL。查看 html_table() 函数描述,我没有找到任何包含这些选项的选项。是否有其他软件包或方法可以做到这一点?

library("rvest")

url <- "http://en.wikipedia.org/wiki/List_of_The_Simpsons_episodes"

simp <- url %>%
        html() %>%
        html_nodes(xpath='//*[@id="mw-content-text"]/table[3]') %>%
        html_table()

simp <- simp[[1]]

【问题讨论】:

  • “..保留 URL”是什么意思?我在这里看到的唯一方法是创建一个列并填写相关的 URL。
  • “保留”,意思是“我想保留的单元格中有一个 href 标签”。

标签: r web-scraping rvest


【解决方案1】:

试试这个

library(XML)
library(httr)
url <- "http://en.wikipedia.org/wiki/List_of_The_Simpsons_episodes"
doc <- content(GET(url))
getHrefs <- function(node, encoding) {  
  x <- xmlChildren(node)$a 
  if (!is.null(x)) paste0("http://", parseURI(url)$server, xmlGetAttr(x, "href"), " | ", xmlValue(x) ) else xmlValue(xmlChildren(node)$text) 
}
tab <- readHTMLTable(doc, which = 3, elFun = getHrefs)
head(tab[, 1:4])
# No. in\nseries No. in\nseason                                                                                              Title                                                               Directed by
# 1              1              1 http://en.wikipedia.org/wiki/Simpsons_Roasting_on_an_Open_Fire | Simpsons Roasting on an Open Fire http://en.wikipedia.org/wiki/David_Silverman_(animator) | David Silverman
# 2              2              2                                     http://en.wikipedia.org/wiki/Bart_the_Genius | Bart the Genius                                                           David Silverman
# 3              3              3                    http://en.wikipedia.org/wiki/Homer%27s_Odyssey_(The_Simpsons) | Homer's Odyssey                      http://en.wikipedia.org/wiki/Wes_Archer | Wes Archer
# 4              4              4       http://en.wikipedia.org/wiki/There%27s_No_Disgrace_Like_Home | There's No Disgrace Like Home                    http://en.wikipedia.org/wiki/Gregg_Vanzo | Gregg Vanzo
# 5              5              5                                   http://en.wikipedia.org/wiki/Bart_the_General | Bart the General                                                           David Silverman
# 6              6              6                                           http://en.wikipedia.org/wiki/Moaning_Lisa | Moaning Lisa                                                                Wes Archer

URL 被保留并由文本中的竖线 (|) 分隔。因此,您可以使用strsplit(as.character(tab[, 3]), split = " | ", fixed = TRUE) 将其拆分。

【讨论】:

  • 很好,效果很好,也适用于其他 WP URL。您能详细说明一下 getHrefs 函数的作用吗?
  • 该函数评估table 的每个孩子:如果它包含一个锚a,则返回它的href 属性(前面是协议和基本url)加上链接文本。如果没有,它只返回子文本。
猜你喜欢
  • 2019-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-03
  • 1970-01-01
  • 2017-09-13
  • 2015-04-28
  • 2021-09-04
相关资源
最近更新 更多