【发布时间】:2016-01-06 00:40:40
【问题描述】:
我在尝试下载 PDF 时遇到了 cookie。
例如,如果我在 Archeology Data Service 上有一个 PDF 文档的 DOI,它将解析为 this landing page 带有embedded link in it to this pdf 但实际上重定向到this 其他链接。
library(httr) 将处理 DOI 解析,我们可以使用 library(XML) 从登录页面提取 pdf URL,但我无法获取 PDF 本身。
如果我这样做:
download.file("http://archaeologydataservice.ac.uk/archiveDS/archiveDownload?t=arch-1352-1/dissemination/pdf/Dyfed/GL44004.pdf", destfile = "tmp.pdf")
然后我收到一个与http://archaeologydataservice.ac.uk/myads/相同的HTML文件
在How to use R to download a zipped file from a SSL page that requires cookies 尝试答案会导致我这样做:
library(httr)
terms <- "http://archaeologydataservice.ac.uk/myads/copyrights"
download <- "http://archaeologydataservice.ac.uk/archiveDS/archiveDownload"
values <- list(agree = "yes", t = "arch-1352-1/dissemination/pdf/Dyfed/GL44004.pdf")
# Accept the terms on the form,
# generating the appropriate cookies
POST(terms, body = values)
GET(download, query = values)
# Actually download the file (this will take a while)
resp <- GET(download, query = values)
# write the content of the download to a binary file
writeBin(content(resp, "raw"), "c:/temp/thefile.zip")
但在 POST 和 GET 函数之后,我只需获得与 download.file 相同的 cookie 页面的 HTML:
> GET(download, query = values)
Response [http://archaeologydataservice.ac.uk/myads/copyrights?from=2f6172636869766544532f61726368697665446f776e6c6f61643f61677265653d79657326743d617263682d313335322d3125324664697373656d696e6174696f6e2532467064662532464479666564253246474c34343030342e706466]
Date: 2016-01-06 00:35
Status: 200
Content-Type: text/html;charset=UTF-8
Size: 21 kB
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "h...
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; c...
<title>Archaeology Data Service: myADS</title>
<link href="http://archaeologydataservice.ac.uk/css/u...
...
看http://archaeologydataservice.ac.uk/about/Cookies好像这个站点的cookie情况比较复杂。似乎这种 cookie 复杂性对于英国数据提供商来说并不罕见:automating the login to the uk data service website in R with RCurl or httr
我如何使用 R 绕过本网站上的 cookie?
【问题讨论】:
标签: r curl web-scraping httr