代码之家  ›  专栏  ›  技术社区  ›  ChinookJargon

将webscraping与for循环相结合

  •  0
  • ChinookJargon  · 技术社区  · 8 年前


    我最初的方法是分别下载每个数据集,并使用rbind()制作一个大数据集:

    library(tidyverse)
    library(rvest)
    
    uber <- read_html("http://h1bdata.info/index.php?em=Uber&job=&city=&year=All+Years") %>%
      html_node("#myTable") %>%
      html_table()
    
    airbnb <- read_html("http://h1bdata.info/index.php?em=Airbnb&job=&city=&year=All+Years") %>%
      html_node("#myTable") %>%
      html_table()
    
    rbind(uber, airbnb)
    

    #I created a list of the tech companies for my loop index
    tech.companies <-as.list(c("Airbnb", "Amazon", "Apple", "Facebook", "Google", "Linkedin", "Microsoft", "Twitter", "Uber", "Yahoo"))
    
    #I then create the loop.  This has been my "best" attempt
    for(i in 1:length(tech.companies)) {
      url <- paste0("http://h1bdata.info/index.php?em=", i, "&job=&city=&year=All+Years")
      tble <- read_html(url) %>%
        html_node("#myTable") %>%
        html_table()
      }
    

    如果您能分享任何见解,我们将不胜感激。

    1 回复  |  直到 8 年前
        1
  •  1
  •   TomS    8 年前

    一般来说,我有印象循环是避免在R在可能的情况下。然而,在这种情况下,我更喜欢使用循环,但原因可能是我开始在Matlab中编码(循环更常见)。如果您坚持应用函数(我无法提供性能基准),则可以在列表中预先定义在每次循环迭代中生成的所有URL/参数,编写刮取函数并运行[s]apply[list,myfun()]

    就你的情况而言,我想要一份清单,因为你显然希望每个雇主都有一张桌子。在这种情况下,我认为逐行(例如,如果你试图逐项刮取商品价格)没有必要(开放供讨论)

    i 仅返回一个数字,而不是向量中的字符值。所以“ i in 1:length(x) url <- paste0() 不插入公司名称,只插入迭代编号(1:10)。在下面的代码中,您可以看到如何使用“ tech.companies[i]

    tech.companies <- c("Airbnb", "Amazon", "Apple", "Facebook", "Google", "Linkedin", "Microsoft", "Twitter", "Uber", "Yahoo")
    result <- list() # init list (so R knows you store tble in a list)
    
    for(i in 1:length(tech.companies)) {
       url <- paste0("http://h1bdata.info/index.php?em=", tech.companies[i], "&job=&city=&year=All+Years")
       tble <- read_html(url) %>%
          html_node("#myTable") %>%
          html_table()
    
       result[[i]] <- tble 
    }
    

    然后可以访问结果数据。框架,例如,具有以下代码:

    Airbnb <- result[[1]] # result is a data.frame