You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用R和rvest抓取网页中的最终出价与保留价?

解决R语言rvest无法抓取动态渲染的Final Bid和Reserve Price问题

你遇到的核心问题是:目标页面使用Vue框架动态渲染内容,静态HTML中仅包含模板占位符(如[%% bid_value|multi_currency %%]),而非实际价格数据。rvest默认仅获取静态HTML,因此无法直接提取渲染后的价格。以下是两种可行解决方案:


方案1:使用RSelenium模拟浏览器渲染

通过控制真实浏览器加载页面并执行JS,获取完全渲染后的内容,再用rvest提取数据。

代码示例

library(RSelenium)
library(rvest)

# 启动Chrome浏览器(需确保ChromeDriver已安装并配置到系统PATH)
driver <- rsDriver(browser = "chrome", port = 4567L)
remDr <- driver[["client"]]

# 访问目标页面
remDr$navigate("https://www.australianwhiskyauctions.com.au/lot-350169/chichibu-2016-single-heavily-peated-1st-fill-bourbon-cask-6240-for-whisky-abbey-2022")

# 等待页面渲染完成(可根据网络情况调整等待时间)
Sys.sleep(3)

# 获取渲染后的页面源码
page_source <- remDr$getPageSource()[[1]]
html <- read_html(page_source)

# 提取Final Bid
final_bid <- html %>% 
  html_element(xpath = "//span[contains(text(), 'Final Bid')]/following-sibling::div") %>% 
  html_text() %>% 
  trimws()

# 提取Reserve Price(仅当未达到保留价时显示)
reserve_price <- html %>% 
  html_element(xpath = "//span[contains(text(), 'Reserve Price')]/following-sibling::div") %>% 
  html_text() %>% 
  trimws()

# 关闭浏览器会话
remDr$close()
driver$server$stop()

# 输出结果
cat("Final Bid:", final_bid, "\n")
cat("Reserve Price:", reserve_price, "\n")

方案2:提取页面内嵌JSON数据(更高效)

多数Vue应用会将初始渲染数据嵌入页面的<script>标签中(如window.__INITIAL_STATE__变量),直接提取并解析该JSON即可获取原始数据,无需模拟浏览器。

代码示例

library(rvest)
library(jsonlite)

# 获取静态页面源码
url <- "https://www.australianwhiskyauctions.com.au/lot-350169/chichibu-2016-single-heavily-peated-1st-fill-bourbon-cask-6240-for-whisky-abbey-2022"
html <- read_html(url)

# 查找包含拍卖数据的script标签
script_content <- html %>% 
  html_elements("script") %>% 
  html_text() %>% 
  grep("bid_value|reserve_price", ., value = TRUE) %>% 
  .[1]

# 提取JSON内容(需根据实际脚本格式调整正则)
json_str <- gsub("^.*window\\.__INITIAL_STATE__ = |;.*$", "", script_content)
lot_data <- fromJSON(json_str)$lot

# 格式化价格为货币格式
final_bid <- formatC(lot_data$bid_value, format = "f", big.mark = ",", digits = 2)
reserve_price <- formatC(lot_data$reserve_price, format = "f", big.mark = ",", digits = 2)

# 输出结果
cat("Final Bid: AUD", final_bid, "\n")
cat("Reserve Price: AUD", reserve_price, "\n")

注意事项

  • 方案2需根据页面实际脚本结构调整正则表达式和数据提取路径,可通过浏览器开发者工具的「Elements」面板查看<script>标签内容确认。
  • 若能找到页面调用的API接口,直接请求接口获取数据是最高效的方式,可通过浏览器「Network」面板分析XHR请求找到接口URL。

内容的提问来源于stack exchange,提问作者João Paiva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 01:34:56