gpt4 book ai didi

r - 将 PDF 从 iframe 抓取到 R

转载 作者:行者123 更新时间:2023-12-01 11:21:22 24 4
gpt4 key购买 nike

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

如果我单击特定年份的超链接,然后单击特定文档的链接(例如,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) 改变 download.file 调用的 mode 部分和 b) 将“.pdf”添加到 tmp< 的路径末尾,但这些都没有帮助。

最佳答案

您要下载的 pdf 位于主页的 iframe 中,因此您下载的链接仅包含 html。您需要点击 iframe 中的链接才能获得 pdf 的实际链接。在到达直接链接下载 pdf 之前,您需要跳转到多个页面以获取 cookies/临时 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

关于r - 将 PDF 从 iframe 抓取到 R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42400471/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com