ファイルをダウンロードするには、次の 2 つの方法があります。
ファイルの名前を log.html に変更して開くと、ログインが無効になっているようです。これが、html 構造を取得する理由です。ログイン資格情報を URL に追加する必要があります。
html ソース コードから名前と値のペアを取得できます。
<label for="username2">Username:</label>
<input type="text" id="username2" name="form_user" value="" size="12" maxlength="64" class="large">
<span class="label-overlay">
<label for="password2">Password:</label>
<input type="password" name="form_pass" id="password2" value="" size="12" maxlength="64" class="large">
ご覧のとおり、ユーザー名の名前と値のペアは form_user=USERNAME と呼ばれ、パスワードの名前と値のペアは form_pass=PASSWORD と呼ばれます。
これが、curl の userpwd 設定が機能せず、ID や名前を認識しない理由です。
## Url for downloading - Does not contain login credentials.
url <- "http://statcounter.com/p7447608/csv/download_log_file?ufrom=1323783441&uto=1323860282"
USERNAME = 'your username'
PASSWORD = 'your password'
## Url for downloading - Does contain login credentials. Use this one!!
url <- paste( 'http://statcounter.com/p7447608/csv/download_log_file?ufrom=1323783441&uto=1323860282&form_user=', USERNAME, '&form_pass=', PASSWORD, sep = '')
## method one, using download file
download.file(url, destfile = "log.csv" )
csv.data <- read.csv("log.csv" )
head(csv.data)
## method 2 using curl
CAINFO = paste(system.file(package="RCurl"), "/CurlSSL/ca-bundle.crt", sep = "")
cookie = 'cookiefile.txt'
curlH = getCurlHandle(
cookiefile = cookie,
useragent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en - US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6",
header = FALSE,
verbose = TRUE,
netrc = TRUE,
maxredirs = as.integer(20),
followlocation = TRUE,
ssl.verifypeer = TRUE)
destfile = "log2.csv"
content = getBinaryURL(url, curl = curlH, cainfo = CAINFO)
## write to file
writeBin(content, destfile)
## read from binary object
csv.data2 <- read.csv(textConnection(rawToChar(content)))
head(csv.data2)
csv.data2 == csv.data