【问题标题】:Web Scraping multiple pages in series using R使用R连续抓取多个页面
【发布时间】:2017-02-05 21:01:13
【问题描述】:

如何抓取 70 个页面的 html 数据?我在看这个question,但我被一般方法部分的功能卡住了。

#attempt

library(purrr)

url_base <-"https://secure.capitalbikeshare.com/profile/trips/QNURCMF2Q6"

map_df(1:70, function(i) {

cat(".")

pg <- read_html(sprintf(url_base, i))   

data.frame( startd=html_text(html_nodes(pg, ".ed-table__col_trip-start-date")), 
endd=html_text(html_nodes(pg,".ed-table__col_trip-end-date")),
duration=html_text(html_nodes(pg, ".ed-table__col_trip-duration"))
)
}) -> table



#attempt 2 (with just one data column)

url_base <-"https://secure.capitalbikeshare.com/profile/trips/QNURCMF2Q6"


map_df(1:70, function(i) {

page %>% html_nodes(".ed-table__item_odd") %>% html_text()

}) -> table

【问题讨论】:

  • 您的网址应该在某处有一个参数,表示当前页码,然后您应该将其与url_base 一起粘贴以生成实际的网址。现在看来您正尝试访问同一个网址 70 次

标签: r web-scraping


【解决方案1】:

不确定您引用的答案中发生了什么,因此我提供了一个与您想要执行的任务非常相似的示例。

  • 转到网页收集信息,将其添加到数据框,然后转到下一页。

我使用创建的这段代码来跟踪我在此处发布到 stackoverflow 的答案:

login<-"https://stackoverflow.com/users/login?ssrc=head&returnurl=http%3a%2f%2fstackoverflow.com%2f"

library(rvest)
pgsession<-html_session(login)
pgform<-html_form(pgsession)[[2]]
filled_form<-set_values(pgform, email="*****", password="*****")
submit_form(pgsession, filled_form)

#pre allocate the final results dataframe.
results<-data.frame()  

for (i in 1:5)
{
  url<-"http://stackoverflow.com/users/**********?tab=answers&sort=activity&page="
  url<-paste0(url, i)
  page<-jump_to(pgsession, url)
  
  #collect question votes and question title
  summary<-html_nodes(page, "div .answer-summary")
  question<-matrix(html_text(html_nodes(summary, "div"), trim=TRUE), ncol=2, byrow = TRUE)

  #find date answered, hyperlink and whether it was accepted
  dateans<-html_node(summary, "span") %>% html_attr("title")
  hyperlink<-html_node(summary, "div a") %>% html_attr("href")
  accepted<-html_node(summary, "div") %>% html_attr("class")
  
  #create temp results then bind to final results 
  rtemp<-cbind(question, dateans, accepted, hyperlink)
  results<-rbind(results, rtemp)
}

#Dataframe Clean-up
names(results)<-c("Votes", "Answer", "Date", "Accepted", "HyperLink")
results$Votes<-as.integer(as.character(results$Votes))
results$Accepted<-ifelse(results$Accepted=="answer-votes default", 0, 1)

这种情况下的循环仅限于 5 页,需要更改以适合您的应用程序。我用 ****** 替换了用户特定的值,希望这能为您解决问题提供一些指导。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 2016-08-09
    • 2022-01-21
    • 2021-09-30
    • 1970-01-01
    相关资源
    最近更新 更多