2016-01-06 6 views
8

Я пытаюсь загрузить файлы cookie при попытке загрузить PDF-файл.Использование R для приема файлов cookie для загрузки PDF-файла

Например, если у меня есть DOI для PDF документа о службе данных археологии, он будет решать this landing page с embedded link in it to this pdf но на самом деле перенаправляет на this другой ссылке.

library(httr) будет обрабатывать разрешение DOI, и мы можем извлечь pdf-адрес с целевой страницы, используя library(XML), но я застрял в получении самого PDF.

Если я это сделать:

download.file("http://archaeologydataservice.ac.uk/archiveDS/archiveDownload?t=arch-1352-1/dissemination/pdf/Dyfed/GL44004.pdf", destfile = "tmp.pdf") 

тогда я получаю HTML-файл, который является таким же, как http://archaeologydataservice.ac.uk/myads/

Trying ответ на 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 Я просто получаю HTML-версию той же самой страницы cookie, что и у меня с download.file:

> 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, кажется, что ситуация печенья на этом сайте сложно. Похоже, эта сложность в отношении печенья не является необычной для британских поставщиков данных: automating the login to the uk data service website in R with RCurl or httr

Как я могу использовать R, чтобы пройти мимо файлов cookie на этом веб-сайте?

ответ

6

Ваша жалоба на rOpenSci была услышана!

Существует много javascript между этими страницами, что делает его несколько раздражающим, чтобы попытаться расшифровать через httr + rvest. Попробуйте RSelenium. Это работало на OS X 10.11.2, R 3.2.3 & Загружен Firefox.

library(RSelenium) 

# check if a sever is present, if not, get a server 
checkForServer() 

# get the server going 
startServer() 

dir.create("~/justcreateddir") 
setwd("~/justcreateddir") 

# we need PDFs to download instead of display in-browser 
prefs <- makeFirefoxProfile(list(
    `browser.download.folderList` = as.integer(2), 
    `browser.download.dir` = getwd(), 
    `pdfjs.disabled` = TRUE, 
    `plugin.scan.plid.all` = FALSE, 
    `plugin.scan.Acrobat` = "99.0", 
    `browser.helperApps.neverAsk.saveToDisk` = 'application/pdf' 
)) 
# get a browser going 
dr <- remoteDriver$new(extraCapabilities=prefs) 
dr$open() 

# go to the page with the PDF 
dr$navigate("http://archaeologydataservice.ac.uk/archives/view/greylit/details.cfm?id=17755") 

# find the PDF link and "hit ENTER" 
pdf_elem <- dr$findElement(using="css selector", "a.dlb3") 
pdf_elem$sendKeysToElement(list("\uE007")) 

# find the ACCEPT button and "hit ENTER" 
# that will save the PDF to the default downloads directory 
accept_elem <- dr$findElement(using="css selector", "a[id$='agreeButton']") 
accept_elem$sendKeysToElement(list("\uE007")) 

Ждем завершения загрузки. Консоль R не будет занята во время загрузки, поэтому легко закрыть сеанс, прежде чем загрузка завершится.

# close the session 
dr$close() 
+0

Попробуйте Ubuntu 14.04, R 3.2.3 и Firefox. 'dr $ open()' reports '[1]« Подключение к удаленному серверу » Неопределенная ошибка в вызове RCurl.Error в queryRD (paste0 (serverURL,«/session »),« POST », qdata = toJSON (serverOpts)): ' –

+1

Это всегда был мой самый большой нит, чтобы выбрать с Селеном вообще (не обязательно R pkg). Согласование между Windows, OS X & * nix настолько сложно.Надеюсь, люди могут добавить к этому (все мои системы * nix очень тонко сконфигурированы безголовыми серверными вещами, и я не собираюсь сегодня осваивать драйвер phantomjs :-) – hrbrmstr

+2

Хорошо, нашел, как заставить его работать на моем компьютер. Мне пришлось вручную запустить автономный сервер selenium сначала с помощью java -jar selenium-server-standalone-2.48.0.jar'. Тогда я могу подключиться. –

3

Этот ответ пришел из John Harrison по электронной почте, размещены здесь по его просьбе:

Это позволит вам скачать PDF:

appURL <- "http://archaeologydataservice.ac.uk/archiveDS/archiveDownload?t=arch-1352-1/dissemination/pdf/Dyfed/GL44004.pdf" 
library(RCurl) 
library(XML) 
curl = getCurlHandle() 
curlSetOpt(cookiefile="cookies.txt" 
      , curl=curl, followLocation = TRUE) 
pdfData <- getBinaryURL(appURL, curl = curl, .opts = list(cookie = "ADSCOPYRIGHT=YES")) 
writeBin(pdfData, "test2.pdf") 

Вот более длинная версия, показывая его рабочий

appURL <- "http://archaeologydataservice.ac.uk/archiveDS/archiveDownload?t=arch-1352-1/dissemination/pdf/Dyfed/GL44004.pdf" 
library(RCurl) 
library(XML) 
curl = getCurlHandle() 
curlSetOpt(cookiefile="cookies.txt" 
      , curl=curl, followLocation = TRUE) 
appData <- getURL(appURL, curl = curl) 

# get the necessary elements for the POST that is initiated when the ACCEPT button is pressed 

doc <- htmlParse(appData) 
appAttrs <- doc["//input", fun = xmlAttrs] 
postData <- lapply(appAttrs, function(x){data.frame(name = x[["name"]], value = x[["value"]] 
                , stringsAsFactors = FALSE)}) 
postData <- do.call(rbind, postData) 

# post your acceptance 
postURL <- "http://archaeologydataservice.ac.uk/myads/copyrights.jsf;jsessionid=" 
# get jsessionid 
jsessionid <- unlist(strsplit(getCurlInfo(curl)$cookielist[1], "\t"))[7] 

searchData <- postForm(paste0(postURL, jsessionid), curl = curl, 
         "j_id10" = "j_id10", 
         from = postData[postData$name == "from", "value"], 
         "javax.faces.ViewState" = postData[postData$name == "javax.faces.ViewState", "value"], 
         "j_id10:_idcl" = "j_id10:agreeButton" 
         , binary = TRUE 
) 
con <- file("test.pdf", open = "wb") 
writeBin(searchData, con) 
close(con) 


Pressing the ACCEPT button on the page you gave initiates a POST to "http://archaeologydataservice.ac.uk/myads/copyrights.jsf;jsessionid=......" via some javascript. 
This post then redirects to the page with the pdf having given some additional cookies. 

Checking our cookies we see: 

> getCurlInfo(curl)$cookielist 
[1] "archaeologydataservice.ac.uk\tFALSE\t/\tFALSE\t0\tJSESSIONID\t3d249e3d7c98ec35998e69e15d3e" 
[2] "archaeologydataservice.ac.uk\tFALSE\t/\tFALSE\t0\tSSOSESSIONID\t3d249e3d7c98ec35998e69e15d3e" 
[3] "archaeologydataservice.ac.uk\tFALSE\t/\tFALSE\t0\tADSCOPYRIGHT\tYES"   

so it would probably be sufficient to set that last cookie to start with (indicating we accept copyright) 
Смежные вопросы