首页 > 解决方案 > 在 Rstudio 中使用 rvest 抓取时,我得到了与网络上不同的 html 文本

问题描述

所以我试图为即将到来的足球比赛制作一个日历(数据框)。我一个一个地抓取这些列,因为我不需要它们。当用时间日期(HORA)抓取列时,我得到一个不正确的值,不知道为什么......我认为它不必与时区一起,因为它只是文本。

library(rvest)
url <- "https://www.cruzados.cl/competitions/campeonato-nacional"
page <- read_html(url)

hora_inicio <- page %>% html_nodes("td.team-schedule__time") %>% html_text()

> hora_inicio
[1] "21:00" "22:30" "23:15" "22:30" "00:30" "00:00" "02:00" "02:00" "19:00" "22:00" "19:00" "22:15" "19:00" "02:00"
[15] "19:00" "19:00" "19:00" "19:00" "19:00" "19:00" "19:00" "19:00" "19:00" "19:00" "19:00" "19:00" "19:00" "19:00"
[29] "19:00" "19:00" "19:00" "19:00" "19:00" "20:00" "20:00" "20:00" "20:00" "20:00" "20:00"

正确的是: 18:00, 19:30, 19:15, 18:30, 20:30, 20:00, 18:00 , ...

标签: rweb-scrapingrvesthtmltext

解决方案


实际上,html 结果中显示的日期时间是 UTC 时区。JS 正在根据您的时区更新结果。

以下将提取日期和时间,将它们组合起来并将 UTC 日期时间转换为您当前的时区:

library(rvest)

url <- "https://www.cruzados.cl/competitions/campeonato-nacional"
page <- read_html(url)

Sys.setlocale(locale="es_ES.UTF-8")

date <- page %>% html_nodes("td.team-schedule__date") %>% html_text()
time <- page %>% html_nodes("td.team-schedule__time") %>% html_text()

dates <- as.Date(gsub("sept", "sep", date), format="%a. %d / %b. / %Y") #dom. 21 / mar. / 2021

i <- 1
tzDates <- list()
for(date in as.list(dates)) {
  utcDate <- as.POSIXct(paste0(format(date, "%Y-%m-%d")," ",time[i]), format="%Y-%m-%d %H:%M",tz = "UTC")
  tzDates[[i]] <- as.POSIXlt(utcDate, tz = Sys.timezone())
  i <- i+1
}
print(tzDates)

您将需要语言环境es_ES.UTF-8es_CL.UTF-8进行安装以获取西班牙语的缩写月份/工作日。


就我而言,我位于法国,您可以看到 3 月 28 日从UTC+1 到 UTC+2的时间变化:

[1] "2021-03-21 22:00:00 CET"
[2] "2021-03-29 00:30:00 CEST"
[3] "2021-04-05 01:15:00 CEST"

返回的 html 是 (UTC) :

[1] "2021-03-21 21:00"
[2] "2021-03-28 22:30"
[3] "2021-04-04 23:15"

推荐阅读