【发布时间】:2019-10-09 15:25:13
【问题描述】:
我正在尝试为 CSI 抓取 wiki 页面上的所有表格:https://en.wikipedia.org/wiki/List_of_CSI:_Crime_Scene_Investigation_episodes 到目前为止一切顺利,我已经能够用下面的代码刮一张桌子(第 1 季), 是否有一个 for 循环可以遍历所有表,因为它们具有相同的类?
这是我的 R 代码
library(rvest)
url <- "https://en.wikipedia.org/wiki/List_of_CSI:_Crime_Scene_Investigation_episodes"
episodes <- url %>%
read_html() %>%
html_nodes('#mw-content-text > div > table:nth-child(14)') %>%
html_table()
episodes <- episodes[[1]]
更新我刚刚意识到每个表选择器都有一个不同的第 n 个子选择器,所以我决定将每个表选择器分配给如下所示的变量。我现在可以遍历每个表并将结果分配给一个 DF/变量“情节”吗 调整代码:
library(dplyr)
library(purrr)
url <- "https://en.wikipedia.org/wiki/List_of_CSI:_Crime_Scene_Investigation_episodes"
table1<- '#mw-content-text > div > table:nth-child(14)'
table2<- '#mw-content-text > div > table:nth-child(18)'
table3<- '#mw-content-text > div > table:nth-child(22)'
table4<- '#mw-content-text > div > table:nth-child(26)'
table5<- '#mw-content-text > div > table:nth-child(30)'
table6<- '#mw-content-text > div > table:nth-child(34)'
table7<- '#mw-content-text > div > table:nth-child(38)'
table8<- '#mw-content-text > div > table:nth-child(42)'
table9<- '#mw-content-text > div > table:nth-child(46)'
table10<- '#mw-content-text > div > table:nth-child(50)'
table11<- '#mw-content-text > div > table:nth-child(54)'
table12<- '#mw-content-text > div > table:nth-child(58)'
table13<- '#mw-content-text > div > table:nth-child(62)'
table14<- '#mw-content-text > div > table:nth-child(66)'
table15<- '#mw-content-text > div > table:nth-child(70)'
table16<- '#mw-content-text > div > table:nth-child(74)'
#table17<- '#mw-content-text > div > table:nth-child(79)'
episodes <- url %>%
read_html() %>%
html_nodes(table1) %>%
html_table(fill = T)
episodes <- episodes[[1]]
write.csv(population, file = "test.csv")
【问题讨论】:
-
你到底是什么意思?你想为每个季节刮桌子吗?
-
是的,如果可能的话,我想要一个数据框中的每个季节的表格。到目前为止,我一次可以刮一张桌子。
标签: r web-scraping rvest scrape