我正在做一個網路報廢練習,我想使用下面的 url 獲取下表:
https://en.wikipedia.org/wiki/COVID-19_pandemic_by_country_and_territory
2022 年 4 月 7 日按地點更新的 COVID-19 病例、死亡人數和比率[5]
我右鍵單擊瀏覽器,檢查并希望找到將替換?代碼中以下內容的表 ID/節點。我找不到這個節點。
library(tidyverse)
library(rvest)
# get the data
url <- "https://en.wikipedia.org/wiki/COVID-19_pandemic_by_country_and_territory"
html_data <- read_html(url)
html_data %>%
html_node("??") %>% # how do I get the node containing the table
html_table() %>%
as_tibble()
謝謝
uj5u.com熱心網友回復:
我建議不要使用長而脆弱的 xpath,而是使用更穩定、更快和描述性的 css 選擇器串列。您可以使用特定的父 ID(通常用于匹配的最快方法)和子表類(第二快)組合:
library(magrittr)
library(rvest)
df <- read_html('https://en.wikipedia.org/wiki/COVID-19_pandemic_by_country_and_territory') %>%
html_element('#covid-19-cases-deaths-and-rates-by-location .wikitable') %>%
html_table()
推薦閱讀:
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors
實踐:
https://flukeout.github.io/
uj5u.com熱心網友回復:
使用您的瀏覽器獲取表的 xpath 并使用它而不是"??".
suppressPackageStartupMessages({
library(httr)
library(rvest)
library(dplyr)
})
url <- "https://en.wikipedia.org/wiki/COVID-19_pandemic_by_country_and_territory"
xp <- "/html/body/div[3]/div[3]/div[5]/div[1]/div[15]/div[5]/table"
html_data <- read_html(url)
html_data %>%
html_elements(xpath = xp) %>% # how do I get the node containing the table
html_table() %>%
.[[1]] %>%
select(-1)
#> # A tibble: 218 x 4
#> Country `Deaths / million` Deaths Cases
#> <chr> <chr> <chr> <chr>
#> 1 World[a] 783 6,166,510 495,130,920
#> 2 Peru 6,366 212,396 3,549,511
#> 3 Bulgaria 5,314 36,655 1,143,424
#> 4 Bosnia and Herzegovina 4,819 15,728 375,948
#> 5 Hungary 4,738 45,647 1,863,039
#> 6 North Macedonia 4,433 9,234 307,142
#> 7 Montenegro 4,308 2,706 233,523
#> 8 Georgia 4,212 16,765 1,650,384
#> 9 Croatia 3,833 15,646 1,105,315
#> 10 Czech Republic 3,712 39,816 3,850,902
#> # ... with 208 more rows
由reprex 包于 2022-04-08 創建(v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/457776.html
