我想从这个 train timetable web page 访问数据.在 URL 上使用 rvest 没有给出有用的答案:
> read_html("https://www.scotrail.co.uk/sites/default/files/assets/download_ct/_sr1705_glasgow-edinburgh_via_falkirk_highv2.pdf")
{xml_document}
<html>
[1] <body><p>%PDF-1.5\r%\xe2ãÏÓ\r\n22 0 obj\r<>\rendobj\r \rxref\r22 97\r0000000 ...
[2] <html><p>C*ÐsO\u0086ZFWM\u0086X H$\u0083>\u0083-Ïs\u0086O=Ì\u008c"Lí½/1\u009c\u009fõ\u008e\u0 ...
但是当我在本地将源代码保存为 html 文件时,我可以很好地抓取内容:
> read_html("/path/to/this/file/_sr1705_glasgow-edinburgh_via_falkirk_highv2.html")
{xml_document}
<html dir="ltr" mozdisallowselectionprint="" moznomarginboxes="">
[1] <head>\n<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">\n<meta charset="utf- ...
[2] <body tabindex="1" class="">\n <div id="outerContainer">\n\n <div id="sidebarContainer"> ...
我想使用 URL 进行抓取,而不是手动下载并另存为 html 文件。感觉好像我缺少有关 PDF 的一些基本知识。我对 URL 中的文件扩展名是 .pdf 但 F12 显示 html 感到困惑。
有没有办法直接从这个 URL 中抓取?如果不是,为什么在本地保存会“解决”问题?
最佳答案
如果您将所有 URL 都保存在名为 my_urls
的向量中,您可以遍历它并告诉 R
下载这些文件。
my_urls <- c("www.pdf995.com/samples/pdf.pdf",
"che.org.il/wp-content/uploads/2016/12/pdf-sample.pdf",
"www.africau.edu/images/default/sample.pdf")
save_here <- paste0("document_", 1:3, ".pdf")
for(i in seq_along(my_urls)){
download.file(my_urls[i], save_here[i])
}
或者更优雅一点,使用 mapply()
:
mapply(download.file, my_urls, save_here)
执行后,你会看到你的文件中保存了document_1.pdf
、document_2.pdf
和document_3.pdf
三个PDF文件工作目录。
关于html - 使用 rvest 抓取在线 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46532362/