簡體   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