Web 抓取具有内联图片的 table

Web Scraping a table that has inline pictures

我正在尝试将标题为 Battle Styles 的 table 抓取到数据框中。 https://bulbapedia.bulbagarden.net/wiki/Battle_Styles_(TCG)#Set_lists

问题是许多行包含带有重要信息的图像,这些信息未在 rvest 中提取。

table 应该是这样的:

No.     Card name   Type    Rarity
001/163 Bellsprout  Grass   Common
002/163 Weepinbell  Grass   Uncommon
003/163 Victreebel  Grass   Rare
004/163 Cacnea      Grass   Common
005/163 Cacturne    Grass   Uncommon
006/163 KricketuneV Grass   Ultra-Rare Rare
007/163 Cherubi     Grass   Common
008/163 Cherrim     Grass   Rare Holo
009/163 Carnivine   Grass   Uncommon
010/163 Durant      Grass   Uncommon

而这个 table ^^ 如果我复制 table 并将其粘贴到记事本中,我就能得到。

但是我的图片不包含任何信息。它看起来像这样:

     # A tibble: 184 x 6
   No.     Image `Card name` Type  Rarity Promotion
   <chr>   <lgl> <chr>       <chr> <lgl>  <chr>    
 1 001/163 NA    Bellsprout  ""    NA     Promotion
 2 002/163 NA    Weepinbell  ""    NA     Promotion
 3 003/163 NA    Victreebel  ""    NA     Promotion
 4 004/163 NA    Cacnea      ""    NA     Promotion
 5 005/163 NA    Cacturne    ""    NA     Promotion
 6 006/163 NA    Kricketune  ""    NA     Promotion
 7 007/163 NA    Cherubi     ""    NA     Promotion
 8 008/163 NA    Cherrim     ""    NA     Promotion
 9 009/163 NA    Carnivine   ""    NA     Promotion
10 010/163 NA    Durant      ""    NA     Promotion

图片所需的信息在alt-text中,所以我觉得解决方案应该很简单,但我不知道如何获取它。

这是我的代码:

library(rvest)

BattlestylesURL <- "https://bulbapedia.bulbagarden.net/wiki/Battle_Styles_(TCG)"

temp <- BattlestylesURL %>% 
  read_html %>%
  html_nodes("table")

html_table(temp[16], fill = TRUE)

我认为最令人头疼的是某些列结合了图像和文本,我正试图在同一列中包含来自两者的信息的数据框。例如,第6行的“卡名”是Kricketune V。'Kricketune'是文字,而“V”是图片。

我觉得应该有一种简单的方法可以做到这一点,但我似乎无法理解它。非常感谢帮助!

我发现的例子很相似: 但是,我不知道如何将其应用于这种情况,因为我也试图保留行中的文本。

您可以先获取 table,然后更新这些列。您可以将 ifelse 用于 Type 列,因为您想要的值可以在 th 或子 img 中(如果存在)。有趣的一点是使用正确的 css 选择器,以便仅匹配相关节点以更新 table。

library(rvest)
library(tidyverse)

page <- read_html("https://bulbapedia.bulbagarden.net/wiki/Battle_Styles_(TCG)#Set_lists")

df <- page %>%
  html_node(".multicol .roundy tr:nth-child(2) table") %>%
  html_table(fill = T)

df <- subset(df, No. != "") %>% select(-c(Image))

df$Rarity <- page %>%
  html_nodes("td:nth-child(1) tr table td:nth-child(5) a") %>%
  html_attr("title")
   
df$Type <- map(page %>% html_nodes("td:nth-child(1) tr tr:nth-child(n+2) th:nth-child(4)"), function(x) {
  var_node <- x %>%
    html_node("img") %>%
    html_attr("alt")
  ifelse(is.na(var_node), x %>% html_text(trim = T), var_node)
})