r语言 - 从rvest_session对象中获取非html内容



我试图从URL获取文本文件。从浏览器来看,这相当简单。我只需要"存为"从URL,我得到我想要的文件。起初,我在使用revest登录时遇到了一些麻烦(参见[https://stackoverflow.com/questions/66352322/how-to-get-txt-file-from-password-protected-website-jsp-in-r][1])(我上传了一些可能有用的图片)。当我使用以下代码时:

fileurl <- "http://www1.bolsadecaracas.com/esp/productos/dinamica/downloadDetail.jsp?symbol=BNC&dateFrom=20190101&dateTo=20210101&typePlazo=nada&typeReg=T"
session(fileurl)

我得到了以下内容(注意我是如何被重定向到一个不同的URL的,就像在浏览器中发生的那样,当你试图在没有第一次登录的情况下访问fileurl):

<session> http://www1.bolsadecaracas.com/esp/productos/dinamica/downloadDetail.jsp?symbol=BNC&dateFrom=20190101&dateTo=20210101&typePlazo=nada&typeReg=T
Status: 200
Type:   text/html; charset=ISO-8859-1
Size:   84

我使用以下代码成功登录:

#Define URLs
loginurl <- "http://www1.bolsadecaracas.com/esp/usuarios/customize.jsp"
fileurl <- "http://www1.bolsadecaracas.com/esp/productos/dinamica/downloadDetail.jsp?symbol=BNC&dateFrom=20190101&dateTo=20210101&typePlazo=nada&typeReg=T"
#Create session
pgsession <- session(loginurl)
pgform<-html_form(pgsession)[[1]]   #Get form
#Create a fake submit button as form does not have one
fake_submit_button <- list(name = NULL,
type = "submit",
value = NULL,
checked = NULL,
disabled = NULL,
readonly = NULL,
required = FALSE)
attr(fake_submit_button, "class") <- "input"    
pgform[["fields"]][["submit"]] <- fake_submit_button
#Create and submit filled form
filled_form<-html_form_set(pgform, login="******", passwd="******")
session_submit(pgsession, filled_form)
#Jump to new url
loggedsession <- session_jump_to(pgsession, url = fileurl)
#Output
loggedsession

在我看来,登录是成功的,因为会话输出是完全相同的大小比。txt文件,当我下载它,我不再重定向。查看输出

<session> http://www1.bolsadecaracas.com/esp/productos/dinamica/downloadDetail.jsp?symbol=BNC&dateFrom=20190101&dateTo=20210101&typePlazo=nada&typeReg=T
Status: 200
Type:   text/plain; charset=ISO-8859-1
Size:   32193

然而,每当我尝试用read_html()或类似的方法提取会话的内容时,我得到以下错误:"错误:页面似乎不是html."。我不知道这是否与"Type: text/plain">

运行

loggedsession[["response"]][["content"]]

[1] 0d 0a 0d 0a 0d 0a 0d 0a 0d 0a 7c 30 32 2f 30 31 2f 32 30 31 39 7c 52 7c 31 34 2c 39 30 7c 31 35 2c
[34] 30 30 7c 31 37 2c 38 33 7c 31 33 2c 35 30 7c 39 7c 31 33 2e 35 33 33 7c 32 30 33 2e 30 36 30 2c 31
[67] 39 7c 0a 7c 30 33 2f 30 31 2f 32 30 31 39 7c 52 7c 31 35 2c 30 30 7c 31 37 2c 39 38 7c 31 37 2c 39

关于如何提取文本文件的任何帮助??非常感谢。

PS:在某一时刻,我只是在摆弄函数,我设法得到了一些可以与httr::: get (fileurl)一起工作的东西。这是在尝试了revest功能并成功登录之后。然而,在关闭并打开RStudio后,我无法使用该函数获得相同的输出。

因为rvest内部使用httr包,所以您可以使用httrbase来保存文件。解决方案的关键是您的response(就httr包而言)位于会话对象中:

library(rvest)
library(httr)
httr::content(loggedsession$response, as = "text") %>%
cat(file = "your_file.txt")

更重要的是,如果您的文件是二进制文件(例如zip归档文件),则必须执行:

library(rvest)
library(httr)
httr::content(loggedsession$response, as = "raw") %>%
writeBin(con = 'your_file.zip')

最新更新