ulf*_*der 3 pdf iframe r web-scraping
我正在努力将联合国安理会(UNSC)决议的文本写入R.联合国维持联合国安理会所有决议的在线档案(PDF格式)(此处).所以,从理论上讲,这应该是可行的.
如果我点击特定年份的超链接,然后单击特定文档的链接(例如,这个),我可以在浏览器中看到PDF.当我尝试通过指向download.fileURL栏中的链接下载该PDF时,它似乎工作.当我尝试使用包中的pdf_text函数将该文件的内容读入R pdftools时,我收到一堆错误消息.
这就是我正在尝试的失败.如果你运行它,你会看到我正在谈论的错误消息.
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)
Run Code Online (Sandbox Code Playgroud)
我错过了什么?我认为它与这些文件的可下载版本的链接地址有所不同,这些文件与浏览器内显示的链接地址不同,但我无法弄清楚如何获得前者的路径.我试着右键单击下载图标; 使用Chrome中的"Inspect"选项查看标识为"src"的网址(此链接); 并指出我的其余过程.同样,该download.file部分执行,但我运行时得到相同的错误消息pdf_text.我还试过a)改变mode调用的部分download.file和b)将".pdf"添加到路径的末尾tmp,但这些都没有帮助.
您要下载的pdf位于主页面的iframe中,因此您下载的链接仅包含html.您需要按照iframe中的链接获取pdf的实际链接.在到达下载pdf的直接链接之前,您需要跳转到几个页面以获取cookie /临时URL.
以下是您发布的链接的示例:
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
Run Code Online (Sandbox Code Playgroud)