【发布时间】:2015-08-21 04:24:44
【问题描述】:
我正在尝试使用 R 中的“rvest”和“downloader”包从科罗拉多石油和天然气保护委员会 (COGCC) 自动下载石油和天然气井的文件。
包含特定井文件的表格/表格的链接是; http://ogccweblink.state.co.us/results.aspx?id=12337064
“id=12337064”是井的唯一标识符
表格页面上的文件可以点击下载。 下面是一个例子。 http://ogccweblink.state.co.us/DownloadDocument.aspx?DocumentId=3172781
“DocumentID=3172781”是要下载的文档的唯一文档 ID。在这种情况下,一个 xlsm 文件。文档页面上的其他文件格式包括 PDF 和 xls。
到目前为止,我已经能够编写代码来下载任何井的任何文档,但仅限于第一页。大多数井都有多个页面上的文档,我无法在第 1 页以外的页面上下载文档(所有文档页面都有相似的 URL)
## Extract the document id for document to be downloaded in this case "DIRECTIONAL DATA". Used the SelectorGadget tool to extract the CSS path
library(rvest)
html <- html("http://ogccweblink.state.co.us/results.aspx?id=12337064")
File <- html_nodes(html, "tr:nth-child(24) td:nth-child(4) a")
File <- as(File[[1]],'character')
DocId<-gsub('[^0-9]','',File)
DocId
[1] "3172781"
## To download the document, I use the downloader package
library(downloader)
linkDocId<-paste('http://ogccweblink.state.co.us/DownloadDocument.aspx DocumentId=',DocId,sep='')
download(linkDocId,"DIRECTIONAL DATA" ,mode='wb')
trying URL 'http://ogccweblink.state.co.us/DownloadDocument.aspx?DocumentId=3172781'
Content type 'application/octet-stream' length 33800 bytes (33 KB)
downloaded 33 KB
有谁知道如何修改我的代码以下载其他页面上的文档?
非常感谢!
嗯
【问题讨论】:
-
当您加载该页面时,会出现一个包含
__EVENTARGUMENT=Page%242之类的帖子请求。这个参数似乎控制着你看到的数据。 -
有 rcurl 和 httr here 的线索(使用 firefox 或 chrome 中的开发工具包查看浏览器发送的请求并稍后模仿它们)
-
感谢@user2706569 的建议。我将 Param 更改为
__EVENTARGUMENT=Page$2并重新运行在 link 上找到的以下代码以查看第 2 页的文档,但发布请求仍在第一页显示文档。对代码所做的唯一细微调整是包括eventargument <- as.character("Page$2"); params <- list('__EVENTARGUMENT' = eventargument); html = postForm('http://ogccweblink.state.co.us/results.aspx?id=12337064', .params = params, curl = curl)
标签: html r web-scraping html-parsing