【问题标题】:how to download pdf file with R from web (encode issue)如何使用 R 从 Web 下载 pdf 文件(编码问题)
【发布时间】:2020-01-06 18:41:25
【问题描述】:

我正在尝试使用 R 从网站下载 pdf 文件。当我尝试使用函数 browserURL 时,它仅适用于参数 encodeIfNeeded = T。因此,如果我将相同的 url 传递给函数download.file,返回“cannot open destfile 'downloaded/teste.pdf', reason 'No such file or directory”,即找不到正确的url。

如何更正编码,以便能够以编程方式下载文件? 我需要自动执行此操作,因为要下载一千多个文件。

这是一个最小的可重现代码:

library(tidyverse)
library(rvest)


url <- "http://www.ouvidoriageral.sp.gov.br/decisoesLAI.html"
webpage <- read_html(url)

# scrapping hyperlinks
links_decisoes <- html_nodes(webpage,".borderTD a") %>%
  html_attr("href")

# creating full/correct url
full_links <- paste("http://www.ouvidoriageral.sp.gov.br/", links_decisoes, sep="" )

# browseURL only works with encodeIfNeeded = T
browseURL(full_links[1], encodeIfNeeded = T,
          browser = "C://Program Files//Mozilla Firefox//firefox.exe")
# returns an error
download.file(full_links[1], "downloaded/teste.pdf") 

【问题讨论】:

  • 您的工作目录中是否存在“已下载”文件夹? download.file 不会为您创建尚不存在的新文件夹。 list.dirs(path = ".", recursive = FALSE) 返回什么?

标签: r encode


【解决方案1】:

这里有几个问题。首先,一些文件的链接没有正确格式化为 url - 它们包含空格和其他特殊字符。为了转换它们,您必须使用 url_escape(),它应该可供您使用,因为加载 rvest 也会加载包含 url_escape() 的 xml2。

其次,你保存的路径是相对于你的 R 主目录的,但你并没有告诉 R 这个。您要么需要这样的完整路径:"C://Users/Manoel/Documents/downloaded/testes.pdf",要么需要这样的相对路径:path.expand("~/downloaded/testes.pdf")

这段代码应该能满足你的需要:

library(tidyverse)
library(rvest)

# scraping hyperlinks
full_links <- "http://www.ouvidoriageral.sp.gov.br/decisoesLAI.html" %>%
               read_html()                                           %>%
               html_nodes(".borderTD a")                             %>%
               html_attr("href")                                     %>%
               url_escape()                                          %>%
               {paste0("http://www.ouvidoriageral.sp.gov.br/", .)}

# Looks at page in firefox
browseURL(full_links[1], encodeIfNeeded = T, browser = "firefox.exe")

# Saves pdf to "downloaded" folder if it exists
download.file(full_links[1], path.expand("~/downloaded/teste.pdf"))

【讨论】:

  • 成功了,谢谢。我只需要在函数 download.file 中添加 mode="wb",因为我在 Windows 上。
  • @AllanCameron:你能看看我的问题吗? stackoverflow.com/questions/66996370/…谢谢!
猜你喜欢
  • 2012-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多