【问题标题】:Scraping PDF from iframe into R将 iframe 中的 PDF 抓取到 R 中
【发布时间】:2017-07-13 00:46:50
【问题描述】:

我正在尝试将联合国安理会 (UNSC) 决议的文本抓取到 R 中。联合国以 PDF 格式 (here) 维护所有联合国安理会决议的在线存档。所以,理论上,这应该是可行的。

如果我单击特定年份的超链接,然后单击特定文档的链接(例如,this one),我可以在浏览器中看到 PDF。当我尝试通过将download.file 指向 URL 栏中的链接来下载该 PDF 时,它似乎可以工作。但是,当我尝试使用 pdftools 包中的 pdf_text 函数将该文件的内容读入 R 时,我收到一堆错误消息。

这就是我正在尝试但失败的方法。如果你运行它,你会看到我所说的错误消息。

library(pdftools)
pdflink <- "http://www.un.org/en/ga/search/view_doc.asp?symbol=S/RES/2341(2017)"
tmp <- tempfile()
download.file(pdflink, tmp, mode = "wb")
doc <- pdf_text(tmp)

我错过了什么?我认为这与这些文件的可下载版本的链接地址与浏览器内显示的链接地址不同有关,但我不知道如何获取前任的。我尝试右键单击下载图标;使用 Chrome 中的“检查”选项查看标识为“src”的 URL (this link);并将我的其余过程指向它。同样,download.file 部分执行,但是当我运行pdf_text 时,我得到了相同的错误消息。我还尝试 a) 将调用的 mode 部分更改为 download.file 和 b) 将“.pdf”附加到 tmp 路径的末尾,但这些都没有帮助。

【问题讨论】:

  • 您收到什么错误消息?下载后可以用download.file()打开文件吗?
  • @MrFlick,错误信息栈以error: May not be a PDF file (continuing anyway)开头,包含一堆“非法字符”信息,以Error: PDF parsing failure.结尾
  • 我试过你的代码,下载的 pdf 文件已损坏。当我在浏览器中尝试上述链接时,它也会出现一些错误。链接是否正确?
  • @anonR,是的,链接是正确的。如果我从上面的代码中复制它并将其粘贴到 Chrome 的 url 栏中,我会得到显示相关分辨率的 PDF 的页面。
  • @MrFlick,回答您的另一个问题:是的。如果我使用页面上工具栏上的下载按钮手动下载文件,并使用我的代码中显示的 url 并将 pdf_text 指向该文件,它读取正常。

标签: r pdf iframe web-scraping


【解决方案1】:

您要下载的 pdf 文件位于主页的 iframe 中,因此您下载的链接仅包含 html。 您需要按照 iframe 中的链接获取 pdf 的实际链接。您需要跳转到多个页面以获取 cookie/临时 url,然后才能访问直接链接以下载 pdf。

这是您发布的链接的示例:

rm(list=ls())
library(rvest)
library(pdftools)

s <- html_session("http://www.un.org/en/ga/search/view_doc.asp?symbol=S/RES/2341(2017)")
#get the link in the mainFrame iframe holding the pdf
frame_link <- s %>% read_html() %>% html_nodes(xpath="//frame[@name='mainFrame']") %>%
  html_attr("src")

#go to that link
s <- s %>% jump_to(url=frame_link)

#there is a meta refresh with a link to another page, get it and go there
temp_url <- s %>% read_html() %>%
  html_nodes("meta") %>%
  html_attr("content") %>% {gsub(".*URL=","",.)} 

s <- s %>% jump_to(url=temp_url)

#get the LtpaToken cookie then come back
s %>% jump_to(url="https://documents-dds-ny.un.org/prod/ods_mother.nsf?Login&Username=freeods2&Password=1234") %>%
  back() 

#get the pdf link and download it
pdf_link <- s %>% read_html() %>% 
  html_nodes(xpath="//meta[@http-equiv='refresh']") %>%
  html_attr("content") %>% {gsub(".*URL=","",.)}

s <- s %>% jump_to(pdf_link)
tmp <- tempfile()
writeBin(s$response$content,tmp)
doc <- pdf_text(tmp)
doc

【讨论】:

  • 谢谢。现在,在过去半个世纪的无数决议中迭代它......
猜你喜欢
  • 1970-01-01
  • 2011-12-16
  • 2019-03-24
  • 2017-11-06
  • 1970-01-01
  • 2021-09-16
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
相关资源
最近更新 更多