使用无限滚动刮取动态电子商务页面

时间:2015-04-25 04:46:10

标签: r web-scraping infinite-scroll rvest

我在R中使用rvest进行一些抓取。我知道一些HTML和CSS。

我想获得URI的每个产品的价格:

http://www.linio.com.co/tecnologia/celulares-telefonia-gps/

当你在页面上下载时,新项目会加载(当你进行一些滚动时)。

到目前为止我做了什么:

Linio_Celulares <- html("http://www.linio.com.co/celulares-telefonia-gps/")

Linio_Celulares %>%
  html_nodes(".product-itm-price-new") %>%
  html_text()

我得到了我需要的东西,但仅限于25个第一个元素(默认加载)。

 [1] "$ 1.999.900" "$ 1.999.900" "$ 1.999.900" "$ 2.299.900" "$ 2.279.900"
 [6] "$ 2.279.900" "$ 1.159.900" "$ 1.749.900" "$ 1.879.900" "$ 189.900"  
[11] "$ 2.299.900" "$ 2.499.900" "$ 2.499.900" "$ 2.799.000" "$ 529.900"  
[16] "$ 2.699.900" "$ 2.149.900" "$ 189.900"   "$ 2.549.900" "$ 1.395.900"
[21] "$ 249.900"   "$ 41.900"    "$ 319.900"   "$ 149.900" 

问题:如何获取此动态部分的所有元素?

我想,我可以滚动页面,直到加载所有元素,然后使用html(URL)。但这似乎很多工作(我计划在不同的部分做这个)。应该有一个程序化的工作。

2 个答案:

答案 0 :(得分:23)

正如@nrussell建议的那样,您可以使用RSelenium以编程方式向下滚动页面,然后再获取源代码。

你可以这样做:

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

#navigate to your page
remDr$navigate("http://www.linio.com.co/tecnologia/celulares-telefonia-gps/")

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

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

#parse it
html(page_source[[1]]) %>% html_nodes(".product-itm-price-new") %>%
  html_text()

答案 1 :(得分:0)

library(rvest)
url<-"https://www.linio.com.co/c/celulares-y-tablets?page=1"
page<-html_session(url)

html_nodes(page,css=".price-secondary") %>% html_text()

遍历网站https://www.linio.com.co/c/celulares-y-tablets?page=2和3,依此类推,您很容易抓取数据