readLine을 통해 url 가져오기
if (!require("XML")) install.packages("XML");library(XML)
## Loading required package: XML
if (!require("stringr")) install.packages("stringr");library(stringr)
## Loading required package: stringr
if (!require("ggmap")) install.packages("ggmap");library(ggmap)
## Loading required package: ggmap
## Loading required package: ggplot2
a<-'http://www.pizzaetang.com/findUs/findUs.asp?cPage='
b<-'&sAct=&sido=&gugun=&seeText=&branch_id='
url=paste0(a,3,b)
line=readLines(url,encoding='UTF-8')
head(line,10)
## [1] "<!DOCTYPE html> "
## [2] "<html lang=\"ko\">"
## [3] "<head>"
## [4] "\t<meta charset=\"utf-8\">"
## [5] "\t<title>피자에땅</title>"
## [6] "\t<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\" />"
## [7] "\t<meta name=\"viewport\" content=\"width=1000\" />"
## [8] " "
## [9] " <meta property=\"og:type\" content=\"website\" />"
## [10] " <meta property=\"og:locale\" content=\"ko_KR\" />"
str_detect(line,‘찾을 문자’)는 받아온 url line 중에서 찾을 문자를 가지고 있으면, TRUE 값을 return함. which는 TRUE에 해당하는 숫자값을 return
아래의 코드는 t_gray에 해당하는 값을 line에서 찾아서 가져오라는 코드.
(add<- line[which(str_detect(line,"t_gray"))[-1]])
## [1] "\t\t\t\t\t\t\t\t\t<p class=\"t_gray\">강원 동해시 천곡동 1045-3</p>"
## [2] "\t\t\t\t\t\t\t\t\t<p class=\"t_gray\">경기 안양시동안구 호계동 1072-1</p>"
## [3] "\t\t\t\t\t\t\t\t\t<p class=\"t_gray\">서울 강서구 화곡동 987-6</p>"
## [4] "\t\t\t\t\t\t\t\t\t<p class=\"t_gray\">서울 구로구 개봉동 475 영화상가 104</p>"
## [5] "\t\t\t\t\t\t\t\t\t<p class=\"t_gray\">서울 구로구 구로동 구로중앙로 86</p>"
gsub(‘치환할 값’,‘치환될 값’,자료) gsub는 자료를 변환 할 때 사용됨 따라서 공백을 제거하라는 뜻
(add<- gsub(" ", "", add))
## [1] "\t\t\t\t\t\t\t\t\t<pclass=\"t_gray\">강원동해시천곡동1045-3</p>"
## [2] "\t\t\t\t\t\t\t\t\t<pclass=\"t_gray\">경기안양시동안구호계동1072-1</p>"
## [3] "\t\t\t\t\t\t\t\t\t<pclass=\"t_gray\">서울강서구화곡동987-6</p>"
## [4] "\t\t\t\t\t\t\t\t\t<pclass=\"t_gray\">서울구로구개봉동475영화상가104</p>"
## [5] "\t\t\t\t\t\t\t\t\t<pclass=\"t_gray\">서울구로구구로동구로중앙로86</p>"
.는 아무 문자나 1개의 자리를 뜻하며, +는 적어도 1번 매치되는 것을 의미, ?는 많아야 한번 매치되는것을 의미(자세한건 정규표현식 참고)
‘<.+?>’나’<.*?>‘는 <>괄호 안의 문자를 제거한다는 의미’(.+?)’등으로 활용 가능
아래의 코드는 <>괄호에 해당하는 문자나 ’\t’로 기입되어 있는 문자 제거
(add<- gsub("<.+?>|\t", "", add))
## [1] "강원동해시천곡동1045-3" "경기안양시동안구호계동1072-1"
## [3] "서울강서구화곡동987-6" "서울구로구개봉동475영화상가104"
## [5] "서울구로구구로동구로중앙로86"
alldata<-data.frame(store=NULL,add=NULL)
for(i in 1:58){
url<-paste(a,i,b)
line<-readLines(url,encoding="UTF-8")
(add<- line[which(str_detect(line,"t_gray"))[-1]])
(add<- gsub(" ", "", add))
(add<- gsub("<.+?>|\t", "", add))
(store<-line[which(str_detect(line,"t_gray"))-1][-1])
(store<- gsub("<.+?>|\t", "",store))
(store<- gsub("/", "",store))
#숫자로시작하고-로 끝나는 문자 제거
(store<- gsub("\\d+\\-+", "",store))
#숫자 제거
(store<- gsub("\\d+", "",store))
#가게 전화번호 생성
data<-data.frame(store,add,stringsAsFactors=F)
alldata<-rbind(alldata,data)}
head(alldata)
## store add
## 1 목동점 서울양천구목동773-3목동글로리파크107호
## 2 신정점 서울양천구신정동954-13
## 3 거여점 서울송파구거여동21번지
## 4 속초교동점 강원속초시교동수복로53,1층748-18
## 5 [휴]방이점 서울송파구방이동오금로19길10,1층
## 6 [휴]사당점 서울동작구사당동1001-17