Web抓取在r中返回空



我正试着从彭博社获取价格。我可以得到如下所示的当前价格,但是无法得到之前的价格。是什么错了吗?

library(rvest)
url <- "https://www.bloomberg.com/quote/WORLD:IND"
price <- read_html(url) %>% 
html_nodes("div.overviewRow__66339412a5 span.priceText__06f600fa3e") %>% 
html_text()
prevprice <- read_html(url) %>% 
html_nodes("div.value__7e29a7c90d") %>% 
html_text() #returns 0
prevprice <- read_html(url) %>% 
html_nodes(xpath = '//section') %>%
html_text() %>% 
as.data.frame() #didn't find the price

提前感谢。

所以,至少有两个初始选项:

  1. 从提取信息的脚本标签中提取。当浏览器运行JavaScript时,这些信息用于填充您所看到的页面。使用rest/http, JavaScript不会运行,所以你需要从script标签中提取,而不是在渲染的网页上。
  2. 或者,您可以使用百分比变化和当前价格计算以前的价格。通过舍入,这里可能会有很小的误差。

我在下面的代码中显示了上述两个选项。

我还调整了css选择器列表,使用attribute = value css选择器,以操作符(^)开始。这是为了使代码更加健壮,因为html中的类看起来是动态的,只有类属性值的开始是稳定的。


library(httr2)
library(tidyverse)
library(rvest)
url <- "https://www.bloomberg.com/quote/WORLDT:IND"
headers <- c("user-agent" = "mozilla/5.0")
page <- request(url) |>
((x) req_headers(x, !!!headers))() |>
req_perform() |>
resp_body_html()
# extract direct
prev_price <- page |>
html_text() |>
stringr::str_match("previousClosingPriceOneTradingDayAgo%22%3A(\d+\.?\d+?)%2C") |>
.[, 2]
curr_price <- page |>
html_element("[class^=priceText]") |>
html_text() |>
str_replace_all(",", "") |>
as.numeric()
# calculate
change <- page |>
html_element("[class^=changePercent]") |>
html_text() |>
str_extract("[\d\.]+") |>
as.numeric()
adjustment <- 100 - change
prev_price_calculated <- curr_price * (adjustment / 100)
print(curr_price)
print(change)
print(prev_price)
print(prev_price_calculated)

最新更新