R:使用从RSelenium抓取的数据创建数据框

时间:2019-03-26 15:36:27

标签: r rvest rselenium

我正在从Google图书中抓取一些信息(对NHL团队进行研究),并且我正在使用RSelenium入门:

library(tidyverse)
library(RSelenium) # using Docker
library(rvest)
library(httr)

remDr <- remoteDriver(port = 4445L, browserName = "chrome")
remDr$open()
remDr$navigate("https://books.google.com/")
books <- remDr$findElement(using = "css", "[name = 'q']")
books$sendKeysToElement(list("NHL teams", key = "enter"))
bookElem <- remDr$findElements(using = "xpath",
                           "//h3[@class = 'LC20lb']//parent::a")

links <- sapply(bookElem, function(bookElem){
  bookElem$getElementAttribute("href")
})

以上内容导航到正确的页面,并搜索“ NHL团队”。需要注意的是,其中一些书具有“预览”页面,并且要了解内容(书名,作者等),必须进一步单击“关于这本书”:< / p>

for(link in links) {
  remDr$navigate(link)

  # If statement to get past book previews
  if (str_detect(link, "frontcover")) {

    # Finding elements for "About this book"
    link2 <- remDr$findElements(using = 'xpath', 
                                '//a[@id="sidebar-atb-link" and span[.="About this book"]]')

    # Clicking on the "About this book" links
    link2_about <- sapply(link2, function(link2){
      link2$getElementAttribute('href') 
    })

    duh <- map(link2_about, read_html)

    # NHL book title, author
    nhl_title <- duh %>% 
      map(html_nodes, '#bookinfo > h1 > span.fn > span') %>% 
      map_chr(html_text) %>% 
      print()

    author1 <- duh %>% 
      map(html_nodes, '#bookinfo div:nth-child(1) span') %>% 
      map_chr(html_text) %>% 
      print()

    test_df <- cbind(nhl_title, author1) # ONLY binds the last book/author
    print(test_df)

  } else {          
    print("lol you thought this would work?") # haven't built this part out yet             
  }
} 

我对map的使用会打印出单独的标题/作者,但我不知道如何将它们放入数据框中。每次我使用tibble()map_dfr()时都会出错。上面的for循环列出了标题,然后列出了作者,但未将任何内容放在一起。如何将所有这些绑定在一起成为一个框架?

1 个答案:

答案 0 :(得分:2)

答案很简单。我只需要在for循环上方添加一个空白列表,然后将其添加到循环中即可。例如,

blank_list <- list()

for(link in links) {
....

  blank_list[[link]] <- tibble(nhl_title, author1)
  wow <- bind_rows(blank_list) 
  print(wow)

}

不要使用do.call()或其他选项,bind_rows()的速度比其他方法要快。

相关问题