R Curl在抓取Javascript内容之前是否可以等待几秒钟

fd3cxomn  于 2022-11-13  发布在  Java
关注(0)|答案(1)|浏览(135)

我正在使用RCurl来抓取情绪数据,但我需要让它先等待几秒钟,然后才能抓取,这是我的初始代码:

library(stringr)
library(curl)
links <- "https://www.dailyfx.com/sentiment"
con <- curl(links)
open(con)
html_string <- readLines(con, n = 3000)
html_string[1580:1700] #The data value property is "--" in this case

如何正确添加等待秒数?

pgx2nnw8

pgx2nnw81#

特别感谢@MrFlick为您安排了
curl只提取该网页的源代码,页面上显示的数据在页面加载后通过javascript加载;它不包含在页面源代码中。如果您希望与使用javascript的页面交互,则需要使用类似RSelenium的代码。或者,您需要对javascript进行反向工程以查看数据来自何处,然后可能直接向数据端点而不是HTML页面发出curl请求
话虽如此,我还是使用RSelenium来实现这一点:

library(RSelenium)
library(rvest)
library(tidyverse)
library(stringr)
rD <- rsDriver(browser="chrome", verbose=F, chromever = "103.0.5060.134")
remDr <- rD[["client"]]
remDr$navigate("https://www.dailyfx.com/sentiment")
Sys.sleep(10) #Give the page fully loaded
html <- remDr$getPageSource()[[1]]
html_obj <- read_html(html)

#Take Buy and Sell Sentiment of Specific Assets
buy_sentiment <- html_obj %>% 
  html_nodes(".dfx-technicalSentimentCard__netLongContainer") %>% 
  html_children()
buy_sentiment <- as.character(buy_sentiment[[15]])
buy_sentiment <- as.numeric(str_match(buy_sentiment, "[0-9]+"))
  
sell_sentiment <- html_obj %>% 
  html_nodes(".dfx-technicalSentimentCard__netShortContainer") %>% 
  html_children()
sell_sentiment <- as.character(sell_sentiment[[15]])
sell_sentiment <- as.numeric(str_match(sell_sentiment, "[0-9]+"))

相关问题