Skip to main content
 首页 » 编程设计

python之在 Python 或 R 中读取动态网页 html

2025年01月19日7mengfanrong

我正在尝试自动化抓取网页表格的过程,例如 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(.))] 

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

> head(Indicators) 
   Time Cur.                             Event Actual Forecast Previous  
4 19:50  JPY           BoJ Summary of Opinions                           
5 19:50  JPY              Exports (YoY)  (Feb)            1.9%    12.3%  
6 19:50  JPY              Imports (YoY)  (Feb)           17.1%     7.9%  
7 19:50  JPY              Trade Balance  (Feb)           -100B    -944B  
8 20:01  GBP Rightmove House Price Index (MoM)                     0.8%  
9 21:30  CNY         House Prices (YoY)  (Feb)                     5.0% 

但是,如果我想在 Tomorrow 选项卡中抓取表格,我需要使用 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 包含字符串中所需的表格数据,我只是不知道如何有效地解析以生成 R 代码的结果。我能否以某种方式调用 rpy2 包,它允许在 Python 中使用 R 代码,或者其他人知道以与上述相同的形式提取表格的更简单方法?我如何解析这个html字符串?

请您参考如下方法:

在 R 中使用 RSelenium 我们可以尝试

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()