R语言爬取指定网站数据:日期范围、下拉选项等操作求助
用RSelenium处理BC省发票汇总页面的动态表单操作
为什么不用rvest?
这个页面是动态交互表单,所有选择、提交操作都依赖浏览器渲染的JS事件,rvest仅能抓取静态HTML,无法处理这类需要用户交互的场景,因此必须用RSelenium模拟浏览器行为完成操作。
完整实现步骤
1. 安装并加载依赖包
# 首次运行需安装包 install.packages(c("RSelenium", "wdman", "rvest")) # 加载包 library(RSelenium) library(wdman) library(rvest)
2. 启动浏览器驱动并打开目标页面
# 启动Chrome驱动(确保Chrome已安装,版本需匹配) chrome_driver <- chrome() remDr <- remoteDriver(browserName = "chrome") remDr$open() # 打开目标页面 target_url <- "https://a100.gov.bc.ca/pub/hbs/opq/ftas/invoiceSummary.do?actionType=P400&radSelectedReport=billing" remDr$navigate(target_url) # 等待页面加载(可根据网络情况调整等待时长) Sys.sleep(3)
3. 执行表单操作
3.1 设置日期范围(2022年1月-12月)
通过XPath定位日期输入框,填入指定日期:
# 定位"From Date"输入框并填入起始日期 from_date <- remDr$findElement(using = "xpath", value = "//input[@name='fromDate']") from_date$sendKeysToElement(list("2022/01/01")) # 定位"To Date"输入框并填入结束日期 to_date <- remDr$findElement(using = "xpath", value = "//input[@name='toDate']") to_date$sendKeysToElement(list("2022/12/31"))
3.2 切换产品标签为"all"
定位"all"对应的单选按钮并点击:
# 定位"all"单选按钮(可根据页面实际属性调整定位表达式) all_radio <- remDr$findElement(using = "xpath", value = "//input[@name='product' and @value='all']") all_radio$clickElement()
3.3 遍历所有File type选项并提交
获取下拉框所有选项,循环选择后执行发送操作:
# 定位File type下拉框 file_type_dropdown <- remDr$findElement(using = "xpath", value = "//select[@name='fileType']") # 获取所有选项元素 file_type_options <- file_type_dropdown$findChildElements(using = "xpath", value = ".//option") # 循环处理每个选项 for (option in file_type_options) { # 打印当前处理的选项(可选,用于日志追踪) option_text <- option$getElementText()[[1]] cat("正在处理File type:", option_text, "\n") # 选择当前选项 option$clickElement() # 定位邮箱输入框并填写你的邮箱 email_input <- remDr$findElement(using = "xpath", value = "//input[@name='email']") email_input$clearElement() # 清空原有内容 email_input$sendKeysToElement(list("your-email@example.com")) # 替换为你的实际邮箱 # 点击"Send Data File"按钮 send_button <- remDr$findElement(using = "xpath", value = "//input[@value='Send Data File']") send_button$clickElement() # 等待提交完成(根据页面响应速度调整时长) Sys.sleep(5) # 重新导航回表单页面(提交后可能跳转,需重置表单) remDr$navigate(target_url) Sys.sleep(3) # 重新设置日期和产品标签(页面刷新后需重新选择) from_date <- remDr$findElement(using = "xpath", value = "//input[@name='fromDate']") from_date$sendKeysToElement(list("2022/01/01")) to_date <- remDr$findElement(using = "xpath", value = "//input[@name='toDate']") to_date$sendKeysToElement(list("2022/12/31")) all_radio <- remDr$findElement(using = "xpath", value = "//input[@name='product' and @value='all']") all_radio$clickElement() }
4. 关闭浏览器驱动
# 关闭会话 remDr$close() chrome_driver$stop()
注意事项
- 元素定位的XPath/CSS选择器需根据页面实际HTML结构调整,可通过浏览器开发者工具(F12)查看元素的
name/id/class属性修改定位表达式。 - 若Chrome驱动版本不匹配导致启动失败,可从Chrome官网下载对应版本的驱动,或用
wdman::chrome(version = "指定版本号")指定版本。 Sys.sleep()的等待时长需根据网络速度和页面响应速度调整,避免操作过快导致元素未加载完成。
内容的提问来源于stack exchange,提问作者D-Whiz
相关产品推荐
相关产品推荐

