问题
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