Webscaping Tables 来自维基百科,免费的百科全书
Webscraping Tables From Wikipedia in R
我想知道是否有人有有用的想法或代码来从维基百科抓取 tables。
具体来说,我对维基百科“各县结果”部分的总统选举结果 table 感兴趣。
可以使用以下 link 并向下滚动到“县级结果”部分找到示例 table:https://en.wikipedia.org/wiki/1948_United_States_presidential_election_in_Texas
table 看起来像这样:
我尝试了以下 Whosebug post 中的一些解决方案:Importing wikipedia tables in R
但是,它们似乎不适用于 table 我想在维基百科中抓取的类型。
任何建议、解决方案或代码将不胜感激。谢谢!
利用 rvest
包,您可以获得 table,方法是首先通过 html_element("table.wikitable.sortable")
选择包含所需 table 的元素,然后提取 [=16] =] 通过 html_table()
像这样:
library(rvest)
url <- "https://en.wikipedia.org/wiki/1948_United_States_presidential_election_in_Texas"
html <- read_html(url)
county_table <- html %>%
html_element("table.wikitable.sortable") %>%
html_table()
head(county_table)
#> # A tibble: 6 x 14
#> County `Harry S. Truman… `Harry S. Truman… `Thomas E. Dewey… `Thomas E. Dewe…
#> <chr> <chr> <chr> <chr> <chr>
#> 1 County # % # %
#> 2 Anders… 3,242 62.37% 1,199 23.07%
#> 3 Andrews 816 85.27% 101 10.55%
#> 4 Angeli… 4,377 69.05% 1,000 15.78%
#> 5 Aransas 418 61.02% 235 34.31%
#> 6 Archer 1,599 86.20% 191 10.30%
#> # … with 9 more variables: Strom ThurmondStates’ Rights Democratic <chr>,
#> # Strom ThurmondStates’ Rights Democratic.1 <chr>,
#> # Henry A. WallaceProgressive <chr>, Henry A. WallaceProgressive.1 <chr>,
#> # Various candidatesOther parties <chr>,
#> # Various candidatesOther parties.1 <chr>, Margin <chr>, Margin.1 <chr>,
#> # Total votes cast[11] <chr>
我想知道是否有人有有用的想法或代码来从维基百科抓取 tables。
具体来说,我对维基百科“各县结果”部分的总统选举结果 table 感兴趣。
可以使用以下 link 并向下滚动到“县级结果”部分找到示例 table:https://en.wikipedia.org/wiki/1948_United_States_presidential_election_in_Texas
table 看起来像这样:
我尝试了以下 Whosebug post 中的一些解决方案:Importing wikipedia tables in R
但是,它们似乎不适用于 table 我想在维基百科中抓取的类型。
任何建议、解决方案或代码将不胜感激。谢谢!
利用 rvest
包,您可以获得 table,方法是首先通过 html_element("table.wikitable.sortable")
选择包含所需 table 的元素,然后提取 [=16] =] 通过 html_table()
像这样:
library(rvest)
url <- "https://en.wikipedia.org/wiki/1948_United_States_presidential_election_in_Texas"
html <- read_html(url)
county_table <- html %>%
html_element("table.wikitable.sortable") %>%
html_table()
head(county_table)
#> # A tibble: 6 x 14
#> County `Harry S. Truman… `Harry S. Truman… `Thomas E. Dewey… `Thomas E. Dewe…
#> <chr> <chr> <chr> <chr> <chr>
#> 1 County # % # %
#> 2 Anders… 3,242 62.37% 1,199 23.07%
#> 3 Andrews 816 85.27% 101 10.55%
#> 4 Angeli… 4,377 69.05% 1,000 15.78%
#> 5 Aransas 418 61.02% 235 34.31%
#> 6 Archer 1,599 86.20% 191 10.30%
#> # … with 9 more variables: Strom ThurmondStates’ Rights Democratic <chr>,
#> # Strom ThurmondStates’ Rights Democratic.1 <chr>,
#> # Henry A. WallaceProgressive <chr>, Henry A. WallaceProgressive.1 <chr>,
#> # Various candidatesOther parties <chr>,
#> # Various candidatesOther parties.1 <chr>, Margin <chr>, Margin.1 <chr>,
#> # Total votes cast[11] <chr>