【问题标题】:How to grab the dates from a webpage in R如何从R中的网页中获取日期
【发布时间】:2022-01-18 00:39:05
【问题描述】:

我正在尝试编写一个 R 代码来获取网页中日期列中的日期例如:Mar 23,Sat。我查看了源代码,这些日期不存在。

到目前为止,我已经尝试了以下内容,但没有任何效果(如果这些代码看起来很愚蠢,请原谅我是网络抓取的新手)

webpage <- read_html("https://www.cricbuzz.com/cricket-series/2810/indian-premier-league-2019/matches")
webpage %>% html_nodes(xpath = "//*[@id='series-matches']/div[4]/div[1]") %>% html_text()
#> [1] ""

webpage %>% html_nodes(xpath = "//html/body/div/div[2]/div[4]/div/div[6]/div[2]/span") %>% html_text()
#> [1] ""

webpage %>% html_nodes(xpath = "//html/body/div/div[2]/div[4]/div/div[6]/div[2]/span/ng-binding") %>% html_text()
#> character(0)

webpage %>% html_nodes(".ng-binding") %>% html_text()
#> character(0)

【问题讨论】:

  • 我查看了激活的 URL(没有 JavaScript),但看不到任何日期。我认为这些是通过 JavaScript 以某种方式插入的,这使得抓取变得更加困难。除非有其他聪明的方法,否则您可能需要 RSelenium。

标签: html r web-scraping rvest rselenium


【解决方案1】:

该信息存储在子span 元素的ng-bind 属性中,其直接父元素具有类“schedule-date”。

&lt;div class="cb-col-25 cb-col pad10 schedule-date ng-isolate-scope" ng-show="!filter_set"&gt;&lt;span ng-bind=" 1553351400000| date:'MMM dd, EEE' : '+05:30'" class="ng-binding"&gt;Mar 23, Sat&lt;/span&gt;&lt;/div&gt;

您可以使用 css 选择器列表 .schedule-date &gt; span 来定位这些元素,然后提取 ng-bind 属性值。然后你有一个纪元 Unix 时间戳,加上 UTC 偏移量(印度标准时间)和日期格式说明。

1553351400000| date:'MMM dd, EEE' : '+05:30'

您可以提取时间戳部分并应用相关转换(由管道分隔符后的信息通知)。


library(rvest)
library(tidyverse)
library(stringi)

strings_with_dates <- read_html("https://www.cricbuzz.com/cricket-series/2810/indian-premier-league-2019/matches") %>%
  html_elements(".schedule-date > span") %>%
  html_attr("ng-bind")

dates <- str_match(strings_with_dates, "(\\d+).*") %>%
  .[, 2] %>%
  as.numeric() %>%
  map(function(x) x / 1000) %>%
  unlist() %>%
  as.POSIXct(origin = "1970-01-01", tz = "Asia/Kolkata") %>%
  as.Date() %>%
  stri_datetime_format(format = "MMM dd, EEE")

【讨论】:

    【解决方案2】:

    ARSelenium 获取日期的解决方案,

    url  = 'https://www.cricbuzz.com/cricket-series/2810/indian-premier-league-2019/matches'
    #Launch Browser
    library(RSelenium)
    library(rvest)
    library(dplyr)
    driver = rsDriver(browser = c("firefox"))
    remDr <- driver[["client"]]
    remDr$navigate(url)    
    
    
       
    remDr$getPageSource()[[1]] %>% 
      read_html() %>%   html_nodes('.schedule-date') %>% 
      html_nodes('.ng-binding') %>%  
      html_text() 
    
    [1] "Mar 23, Sat" "Mar 24, Sun" "Mar 25, Mon" "Mar 26, Tue" "Mar 27,               
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-17
      • 2020-05-10
      • 1970-01-01
      • 2011-09-27
      • 1970-01-01
      • 2018-02-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多