用Python或R读取动态网页html

2024-06-01 12:39:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试自动处理诸如Investing.com Economic Calendar之类的网页表格 如果我们只对显示今天的日历的默认选项卡感兴趣,那么R就相当简单了。以下是R代码:

library(rvest)
library(dplyr)

Econ_webpage <- read_html("https://www.investing.com/economic-calendar/")

Indicators  <- Econ_webpage %>% html_nodes("#economicCalendarData") %>% 
html_table(fill = TRUE)  %>% .[[1]] %>% .[-(1:3),-  c(match("Imp.",colnames(.)),ncol(.))]

这将产生下面显示的所需结果。在

^{pr2}$

但是,如果我想明天在tab中清除表,我需要使用Selenium驱动程序。我尝试过RSelenium,但无法在我的机器上运行,所以我尝试了Python中的Selenium。我在Python中使用以下代码:

import selenium
from selenium import webdriver 

driver.Chrome(executable_path=PATH_TO_CHROMEDRIVER)
driver.get("https://www.investing.com/economic-calendar/")
driver.find_element_by_id("timeFrame_tomorrow").click()
html = driver.page_source

现在我有了一个包含所需表数据的html字符串,我只是不知道如何有效地par生成R代码的结果。我可以调用rpy2包吗?rpy2包允许Python中的R代码,或者其他人知道一种更简单的方法来提取与上面相同的表?如何解析这个html字符串?在


Tags: 代码httpsimportcomhtmlwwwdriverselenium
1条回答
网友
1楼 · 发布于 2024-06-01 12:39:21

如果RSeleniumR中,我们可以试试

library(RSelenium)
library(XML)

rD <- rsDriver()
remDr <- rD[["client"]]
remDr$navigate("https://www.investing.com/economic-calendar/")
option <- remDr$findElement("id", "timeFrame_tomorrow")
option$clickElement()
res <- readHTMLTable((remDr$getPageSource()[[1]]))$economicCalendarData
res <- res[-1,]
head(res)
#   Time Cur. Imp.                       Event Actual Forecast Previous 
#2 02:30  GBP      Investing.com GBP/USD Index                    46.5% 
#3 02:30  USD         Investing.com Gold Index                    65.6% 
#4 02:30  USD      Investing.com S&P 500 Index                    70.7% 
#5 02:30  CAD      Investing.com USD/CAD Index                    41.8% 
#6 02:30  CHF      Investing.com USD/CHF Index                    53.8% 
#7 02:30  AUD      Investing.com AUD/USD Index                    47.9% 


remDr$close()
rD[["server"]]$stop() 

相关问题 更多 >