繁体   English   中英

如何在R和Python中刮出带有度数符号的表?

[英]How to scrape a table with degree symbol in R and Python?

我正试图在这个网站上抓取表格

首先,我从这里尝试了R ,代码如下:

url <- paste0("https://artofproblemsolving.com/wiki/index.php/Polygon")
library(tidyverse)
library(rvest)
h <- read_html(url)
class(h)
tab <- h |> html_nodes("table")
tab[[1]]
tab <- tab[[1]] |> html_table()
class(tab)
tab

带有 $\circ$ 的最后两列丢失了; 当我使用此处的代码尝试Python时,同样的问题发生了:

import pandas as pd
URL = "https://artofproblemsolving.com/wiki/index.php/Polygon"
#tables = pd.read_html(URL,match="Number of Sides")
tables=pd.read_html(URL,attrs = {'class' : 'wikitable'})
print(tables)
print("There are : ",len(tables)," tables")
print("Take look at table 0")
tables[0]

我想知道你是否可以帮我解决这个问题,或者建议一种从链接中抓取整个表格的新方法。 谢谢!

这是一个解决方案。 度数位于图像元素中,因此您必须提取它们的“alt”属性。

suppressPackageStartupMessages({
  library(dplyr)
  library(rvest)
})

link <- "https://artofproblemsolving.com/wiki/index.php/Polygon"
page <- read_html(link)

df1 <- page %>%
  html_element('table.wikitable') %>%
  html_table()

angles <- page %>%
  html_element('table.wikitable') %>%
  html_elements('img.latex') %>%
  html_attr('alt') %>%
  gsub("[^[:digit:]]+", "", .) %>%
  as.integer() %>%
  matrix(ncol = 2, byrow = TRUE)

df1[2:3] <- angles
df1
#> # A tibble: 5 × 3
#>   `Number of Sides` `Sum of Interior angles` Individual angle measure in regul…¹
#>               <int>                    <int>                               <int>
#> 1                 3                      180                                  60
#> 2                 4                      360                                  90
#> 3                 5                      540                                 108
#> 4                 6                      720                                 120
#> 5                 8                     1080                                 135
#> # … with abbreviated variable name
#> #   ¹​`Individual angle measure in regular polygon`

创建于 2022-12-26,使用reprex v2.0.2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM