从电子商务页面抓取产品信息

Scrape Products Information from a Ecommerce Page

需要从电子商务页面抓取产品信息。但是页面有无限滚动。目前我只能在不向下滚动的情况下抓取显示的产品。下面是它的代码。

require(RCurl)
require(XML)
require(dplyr)
require(stringr)

webpage <- getURL("http://www.jabong.com/kids/clothing/girls-clothing/kids-tops-t-shirts/?source=topnav_kids")

linklist <- str_extract_all(webpage, '(?<=href=")[^"]+')[[1]]
linklist <- as.data.frame(linklist)
linklist <- filter(linklist, grepl("\?pos=", linklist))
linklist <- unique(linklist)

a <- as.data.frame(linklist)
a[2] <- "Jabong.com"
a <- add_rownames(a, "ID")
a$V3 <- gsub(" ", "", paste(a$V2, a$linklist))
a <- a[, -(1:3)]
colnames(a) <- "Links"

好吧,如果滚动真的是无限的,那么就不可能得到所有的链接...如果你想满足于有限的数量,你确实可以在这里使用 RSelenium

library(RSelenium)

#start RSelenium
checkForServer()
startServer()
remDr <- remoteDriver()
remDr$open()

# load your page
remDr$navigate("http://www.jabong.com/kids/clothing/girls-clothing/kids-tops-t-shirts/?source=topnav_kids")

# scroll down 5 times, allowing 3 second for the page to load everytime
for(i in 1:5){      
  remDr$executeScript(paste("scroll(0,",i*10000,");"))
  Sys.sleep(3)    
}

# get the page html
page_source<-remDr$getPageSource()

# get the URL's that you are looking for
pp <- xml2::read_html(page_source[[1]]) %>% 
  rvest::html_nodes("a") %>% 
  rvest::html_attr("data-original-href") %>% 
  {.[!is.na(.)]}

结果是 312 个链接(在我的浏览器中)。向下滚动 RSelenium 越多,您获得的链接就越多。