2017-12-15 5 views
0

목표 : 특정 조수 스테이션에서 전체 연도의 조수 예측 데이터를 얻습니다 (아래 예제 참조).온라인 사이트 cgi의 데이터 스크래핑 R

시도 : 가장 유사한 것으로 보이는 날씨 데이터에 대한 this exchange을 비롯한 다양한 게시물의 팁. 나는 내가 원하는 데이터를 저장하고있는 사이트가 cgi임을 알아 차렸다. 매개 변수를 선택하면 해당 매개 변수가 링크 주소에 반영되지 않습니다. 나는 데이터 스크래핑에 대해이 문제를 다루는 데 전적으로 익숙하지 않다.

library(RCurl) 
url <- "http://tbone.biol.sc.edu/tide/tideshow.cgi?site=South+Beach%2C+Yaquina+Bay%2C+Oregon&units=f" 

s <- getURL(url) 
s <- gsub("<br>\n", s) 
dat <- read.csv(con <- textConnection(s)) 

이것은 실제로 제품을 준 첫 번째 코드이지만 테이블의 데이터는 아닙니다. 이상적으로 옵션을 선택하고 싶습니다 (예 : 1 년, 시작일을 1 월 1 일로 설정). 나는 이것을 한 번도 해본 적이 없으며 HTML 프로그래밍이나 개발을 통해이 유형의 사이트에서 사용할 도구를 알지 못한다.

+1

그 사이트는 [http://tbone.biol.sc.edu/robots.txt] 누구도 긁어 모으기를 원하지 않습니다. [그것이 보여주는 소프트웨어] (http://www.flaterco.com/xtide/index.html)는 무료입니다. – alistaire

+0

https://cran.r-project.org/web/packages/TideTables/index.html & https://beckmw.wordpress.com/2017/04/12/predicting-tides-in-r/ & http : //lukemiller.org/index.php/2016/09/rtide-ar-package-for-predicting-tide-heights-us-locations-only-currently/ & ... 오하이오, 특히 https://github.com/poissonconsulting/rtide – hrbrmstr

+0

이러한 링크를 보았습니다. 나는 조수 예측에 관심이 없다. 그것은이 사이트에서 나를 위해 이루어집니다. 이 사이트는 여행을 계획 할 때 "전형적인 수확기"가 사용하는 것으로 사용하기 때문에 중요합니다. 난 그냥 CSV로 내보낼 수 있지만, 목표는 사이트에서 직접 정보를 수집하는 것이 었습니다. – KVininska

답변

0

동료의 도움을 받아 GUI 기반 .cgi 사이트에서 여러 기준에 따라 여러 사이트의 데이터를 스크래핑하는 코드는 다음과 같습니다.

여러 사이트 (하이퍼 링크)가 나열된 기본 웹 사이트로 돌아가서 원하는 항목을 선택하고 GUI에서 선택한 기준을 적용한 다음 데이터 프레임에 적절하게 서식을 지정해야했습니다 .

library(rvest) 
library(plyr) 
library(dplyr) 
library(stringr) 

#define base url for region (ie site where multiple locations are) 
url <- "http://tbone.biol.sc.edu/tide/sites_uswest.html" 

#read html from page and extract hyperlinks 
#view url to see list of links for multiple locations 
l <- url %>%read_html()%>% 
    html_nodes("a") %>% html_attr("href") 

# grep only tideshow pattern to get vector of site links 
# grep allows filtering/subsetting using a partial string 
sites <- l[grep("*tideshow*", l)] 

# remove everything before 'site=' to get correct formatting for url site names 
sites <- gsub(".*site=", "", sites) 

#generate vector of sites of interest 
#don't need to use regex to create the vector; 
    #you can manipulate the list of sites however you prefer 
    #here, used | for "or" value for selecting multiple sites at once 
sites <- sites[grep("(Waldport\\%2C\\+Alsea|South\\+Beach\\%2C\\+Yaquina|Charleston\\%2C\\+Oregon)(?!.*\\%282\\%29)", sites, perl=TRUE)] 

#define starting date of data 
year <- "2016" 
month <- "01" 
day <- "01" 

#define number of days for prediction 
numberofdays = 366 +365 #no. of days in 2016 + no. days in 2017 

# lapply through the site vector, x represents site. 
# This will pull data from each site in the vector "sites", and bind it together in a list 
o <- lapply(sites, function(x){ 

    # paste together file path using generalized cgi address and defined parameters 
    path<- paste0("http://tbone.biol.sc.edu/tide/tideshow.cgi?type=table;tplotdir=horiz;gx=640;gy=240;caltype=ndp;interval=00%3A01;glen=", 
       numberofdays , 
       ";fontsize=%2B0;units=feet;", 
       "year=", year, ";month=", month, ";day=", day, 
       ";hour=00;min=01;", 
       "killsun=1;tzone=local;ampm24=24;colortext=black;colordatum=white;colormsl=yellow;colortics=red;colorday=skyblue;colornight=deep-%3Cbr%20%2F%3Eskyblue;colorebb=seagreen;colorflood=blue;site=", 
       x, 
       ";d_year=;d_month=Jan;d_day=01;d_hour=00;d_min=00" 
) 

    # use ReadLines to bring in table from each file. 
    d <- readLines(path, warn=FALSE) 

    # extract site name 
    site <- str_extract(string = d[grep("<h2>", d)][1], pattern = "(?<=<h2>)(.*?)(?=</h2>)") 

    # extract coordinates 
    coord <- gsub(".*<pre>", "", d[grep("<h2>", d)][1]) 

    # get tide data lines 
    data <- d[grep("\\d{4}[-]\\d{1,2}[-]\\d{1,2}", d) ] 

    # bind columns together 
    all <- cbind(site,coord, data) 
}) 

# bind data.frame from list 
df <- ldply(o, rbind.data.frame) 

# bind site and coordinate columns with split data columns 
tides <- cbind(df[c(1,2)] , str_split_fixed(df$data, "\\s+", 6)) 
names(tides) <- c("site", "coordinates", "date", "time", "tz", "depth", "units", "tide") 
head(tides) 
str(tides) 
summary(tides)