2017-08-07 28 views
2

私はRを使用してアマゾンウェブをスクラップし、商品の価格を入手しています。 製品は5ページに存在するので、毎回異なるURLを入力する必要があります。アマゾンウェブを掻き集めるR

pages<-c(1,2,3,4,5) 
##getting the url of the 5 pages 
urls<-rbindlist(lapply(pages,function(x){ 
    url<-paste("https://www.amazon.co.uk/Best-Sellers-Health-Personal-Care-Weight-Loss-Supplements/zgbs/drugstore/2826476031#",x,sep="") 
    data.frame(url) 
}),fill=TRUE) 


product.price<-rbindlist(apply(urls,1,function(url){ 
    locations <- url %>% 
    map(read_html) %>% 
    map(html_nodes, xpath = '//*[@id="zg_centerListWrapper"]/div/div[2]/div/div[2]/span[1]/span') %>% 
    map(html_text) %>% 
    simplify() 
    data.frame(locations) 
}),fill=TRUE) 

が100製品、各ページ内の20があり、私は何を取得していますが、最初の20を5回繰り返しです:私が使用したコードである 。 これは、最初のURLだけを入力したことを意味します。 すべてのページにアクセスするにはどうすればよいですか?ここで

おかげ

答えて

0

が私の感想です:

library(rvest) 

url <- 'https://www.amazon.co.uk/Best-Sellers-Health-Personal-Care-Weight-Loss-Supplements/zgbs/drugstore/2826476031#' 

page <- read_html(url) 

numPages <- page %>% 
    html_node('.zg_pagination') %>% 
    html_nodes('li') %>% 
    length 

items <- vector() 
for(i in 1:numPages){ 
    url <- paste0(url, i) 
    page <- read_html(url) 

    item <- page %>% 
    html_nodes(xpath = '//*[@id="zg_centerListWrapper"]/div/div[2]/div/a/div[2]') %>% 
    html_text(trim = TRUE) 

    items <- append(items, item) 
} 

主な相違点:

  1. 私はループの代わりに、機能的なアプローチ
  2. と一緒に行った、アイテムを取得するために、XPath引数を修正しました名前 - あなたは簡単に価格、星などを得るために拡張することができます
関連する問題