R rvest 编码错误与 UTF-8

R rvest encoding errors with UTF-8

我正在尝试从维基百科获取 this table。 clam 文件的来源是 UTF-8:

> <!DOCTYPE html> <html lang="en" dir="ltr" class="client-nojs"> <head>
> <meta charset="UTF-8"/> <title>List of cities in Colombia - Wikipedia,
> the free encyclopedia</title>
> ...

但是,当我尝试使用 rvest 获取 table 时,它显示奇怪的字符,其中应该有重音符号(标准西班牙语),如 á、é 等。 这就是我的尝试:

theurl <- "https://en.wikipedia.org/wiki/List_of_cities_in_Colombia"
file <- read_html(theurl, encoding = "UTF-8")
tables <- html_nodes(file, "table")
pop <- html_table(tables[[2]])
head(pop)

##   No.         City Population         Department
## 1   1      Bogotá  6.840.116       Cundinamarca
## 2   2    Medellín  2.214.494          Antioquia
## 3   3         Cali  2.119.908    Valle del Cauca
## 4   4 Barranquilla  1.146.359         Atlántico
## 5   5    Cartagena    892.545           Bolívar
## 6   6      Cúcuta    587.676 Norte de Santander

我已尝试按照其他 SO 问题中的建议修复编码:

repair_encoding(pop)

## Best guess: UTF-8 (100% confident)
## Error in stringi::stri_conv(x, from = from) : 
##   all elements in `str` should be a raw vectors

我测试了几种不同的编码(latin1 和 guess_encoding() 提供的其他编码,但它们都产生了类似的错误结果。

如何正确加载此 table?

看来您必须在字符向量上使用 repair_encoding,而不是整个数据帧...

> repair_encoding(head(pop[,2]))
Best guess: UTF-8 (80% confident)
[1] "Bogotá"       "Medellín"     "Cali"         "Barranquilla"
[5] "Cartagena"    "Cúcuta"