scraping with R using rvest and purrr, multiple pages

空扰寡人 提交于 2021-02-11 12:44:53

问题


I am trying to scrape a database containing information about previously sold houses in an area of Denmark. I want to retrieve information from not only page 1, but also 2, 3, 4 etc.

I am new to R but from an tutorial i ended up with this.

library(purrr)
library(rvest)

urlbase <- "https://www.boliga.dk/solgt/alle_boliger-4000ipostnr=4000&so=1&p=%d"
map_df(1:5,function(i){
    cat(".")
    page <- read_html(sprintf(urlbase,i))

    data.frame(Address = html_text(html_nodes(page,".d-md-table-cell a")))
               Price = html_text(html_nodes(page,".text-md-left+ .d-md-table-cell .text-right"))
               Rooms = html_text(html_nodes(page,".d-md-table-cell:nth-child(5) .paddingR"))
               m2 = html_text(html_nodes(page,".qtipped+ .d-md-table-cell .paddingR"))
               stringsAsFactors = FALSE

}) -> BOLIGA.ROSKILDE

View(BOLIGA.ROSKILDE)

Which gives me the message:

Error in bind_rows_(x, .id) : Argument 1 must have names

Any help would be welcome


回答1:


Try this one:

library(rvest)
library(tidyverse)
url="https://www.boliga.dk/solgt/alle_boliger-4000ipostnr=4000?ipostnr=4000ipostnr&so=1&p=1"

# find number of pages in table

   pgs<- ceiling(read_html(url)%>%
                html_nodes(".d-print-none")%>%
                html_nodes("b")%>%
                html_text()%>%
                gsub("[^\\d]+", "", ., perl=TRUE)%>%
                as.numeric()
              /40)

#scrap our table 

scrap=function(pg){
  url=paste0("https://www.boliga.dk/solgt/alle_boliger-4000ipostnr=4000?ipostnr=4000ipostnr&so=1&p=",pg)
  return( read_html(url)%>%
  html_node(".searchResultTable")%>%
  html_table()%>%
  .[,c(1,2,5,4)]%>%
    magrittr::set_colnames(c("Address","Price","Rooms","m2"))%>%
    mutate(m2=as.numeric(m2))
  )
}

#purrr for each page

df=seq(1,pgs)%>%
  map_df(.,scrap)


来源:https://stackoverflow.com/questions/51878165/scraping-with-r-using-rvest-and-purrr-multiple-pages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!