在 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,...

解决方法

实际上,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 to 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"

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...