【问题标题】:Scrape multiple tables from Wikipedia in R在 R 中从 Wikipedia 中抓取多个表
【发布时间】:2020-04-19 23:01:03
【问题描述】:

我正在尝试使用 R 中的 rvest 库来抓取此 Wiki 页面的内容

(https://en.wikipedia.org/wiki/List_of_Bollywood_films_of_2019)

我想提取 4 个表格,其中包含 2019 年(1 月至 3 月、4 月至 6 月、7 月至 9 月、10 月至 12 月)宝莱坞电影的上映数据

已经完成了

library(rvest)
url <- "https://en.wikipedia.org/wiki/List_of_Bollywood_films_of_2019"
webpage <- read_html(url)
tbls <- html_nodes(webpage, "table")

#Then I match with the word opening & I get 4 tables as in wikipedia page, however I am struggling to combine them into one dataframe & store it 

tbls[grep("Opening",tbls,ignore.case = T)]

这会出错

df <- html_table(tbls[grep("Opening",tbls,ignore.case = T)],fill = T)

我明白,因为它返回了多个表,我在某个地方缺少一些下标,不确定在哪里。救命!

【问题讨论】:

  • This question 似乎很有帮助。
  • 如该链接和documentation 的第 8 页中所示,对于 html_table 有这样的期望:没有单元格跨越多行

标签: r web-scraping tidyverse rvest


【解决方案1】:

这是适合您的一种方法,而我相信还有更好的方法来处理您的案件。当您使用rvest 包时,您可以使用SelectGadget。您会看到链接中有 15 个表。首先,您要抓取所有表并创建一个列表对象。然后,您希望使用列信息对列表进行子集化。您要抓取的表具有 Opening 作为列名。因此,我使用逻辑检查来测试每个列表元素中是否存在具有该名称的列,并获得了您想要的四个表。

library(tidyverse)
library(htmltab)

map(.x = 1:15,
    .f = function(mynum) {htmltab(doc = "https://en.wikipedia.org/wiki/List_of_Bollywood_films_of_2019",
                                  which = mynum, rm_nodata_cols = F)}) -> res

Filter(function(x) any(names(x) %in% "Opening"), res) -> out

【讨论】:

  • 有趣的+。我尝试过运行它。使用 rvest,您可以使用 html_nodes('.wikitable:not(.sortable)') 获得正确的表,但这并不能解决整体问题。
  • @QHarr 我也尝试在html_nodes() 中使用wikitable,但找不到任何解决方案。所以我正在寻找一种解决方法。
  • @QHarr 谢谢。如果您能想到任何其他方式,请随时在此处修改我的建议。
  • 大声笑。没有。我用 htmlTable 包掉进了兔子洞
  • @QHarr 我不太了解这个包。我想在 2020 年学习它。
【解决方案2】:

对于复杂的HTML表格,我推荐htmltab包:

library(purrr)
library(htmltab)

url <- "https://en.wikipedia.org/wiki/List_of_Bollywood_films_of_2019"
tbls <- map2(url, 4:7, htmltab)
tbls <- do.call(rbind, tbls)

【讨论】:

  • 这很完美,只是演员的名字之间没有分隔符,因此很难分开。你能帮忙吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-26
  • 1970-01-01
相关资源
最近更新 更多