【问题标题】:Web scraping and looping through pages with R使用 R 进行网页抓取和循环浏览页面
【发布时间】:2019-09-23 01:32:45
【问题描述】:

我正在学习数据抓取,除此之外,我还是 R 的新手(在工作中我使用 STATA,我只将 R 用于非常具体的任务)。 为了学习刮痧,我在《今日心理学》上练习了几页。

我编写了一个函数,允许我为一位治疗师抓取信息,并使用以这种方式收集的信息创建一个数据集:

install.packages('rvest') #Loading the rvest package
install.packages('xml2') #Loading the xml2 package
library('rvest') #to scrape
library('xml2')  #to handle missing values (it works with html_node, not with html_nodes)

#Specifying the url for desired website to be scraped
url <- 'https://www.psychologytoday.com/us/therapists/THE_ONE_YOU_WANT'

#Reading the HTML code from the website
URL <- read_html(url)

#creating the function
getProfile <- function(profilescrape) {

      ##NAME
            #Using CSS selectors to name
            nam_html <- html_node(URL,'.contact-name')
            #Converting the name data to text
            nam <- html_text(nam_html)
            #Let's have a look at the rankings
            head(nam)
            #Data-Preprocessing: removing '\n' (for the next informations, I will keep \n, to help 
            #                                   me separate each item within the same type of 
            #                                   information)
            nam<-gsub("\n","",nam)
            head(nam)
            #Convering each info from text to factor
            nam<-as.factor(nam)
            #Let's have a look at the name
            head(nam)


        ##MODALITIES
            #Using CSS selectors to modality
            mod_html <- html_node(URL,'.attributes-modality .copy-small')
            #Converting the name data to text
            mod <- html_text(mod_html)
            #Let's have a look at the rankings
            head(mod)
            #Convering each info from text to factor
            mod<-as.factor(mod)
            #Let's have a look at the rankings
            head(mod)


        ##Combining all the lists to form a data frame
              onet_df<-data.frame(Name = nam,
                                  Modality = mod)

        ##Structure of the data frame
        str(onet_df)

            }

View(onet_df)

无论我选择什么治疗师,这段代码似乎都适用。 现在,我想在多个配置文件上使用此功能,以生成一个数据集,其中包含 MHP 的名称和模态。 假设我想将上述函数“getProfile”应用于伊利诺伊州的前 20 位治疗师,并将这 20 位治疗师的信息输入一个名为“onet_df”的数据集中

j <- 1
MHP_codes <-  c(324585 : 449807) #therapist identifier
withinpage_codes <-  c(1 : 20) #therapist running number
  for(code1 in withinpage_codes) {
    for(code2 in MHP_codes) {
      URL <- paste0('https://www.psychologytoday.com/us/therapists/illinois/', code2, '?sid=5d87f874630bd&ref=', code1, '&rec_next=1&tr=NextProf')
      record_profile <- getProfile <- function(profilescrape)
      onet_df[[j]] <- rbind.fill(onet_df, record_profile)
      j <- j + 1
      }
}

编辑从这里开始:

这个循环不会创建任何数据集;此外,它没有给出任何错误信息。 有人能帮我调试这个循环吗? 请记住,我是一个真正的初学者。

根据建议,我修改了开头的内容:

#creating the function
getProfile <- function(URL) {....}

此外,我使用了三个替代循环:

第一种选择

j <- 1
MHP_codes <-  c(324585 : 449807) #therapist identifier
withinpage_codes <-  c(1 : 20) #therapist running number
for(code1 in withinpage_codes) {
  for(code2 in MHP_codes) {
    URL <- paste0('https://www.psychologytoday.com/us/therapists/illinois/', code2, '?sid=5d87f874630bd&ref=', code1, '&rec_next=1&tr=NextProf')
    record_profile <- getProfile(URL)
      onet_df[[j]] <- rbind.fill(onet_df, record_profile)
    j <- j + 1
  }
}

给出以下错误消息: UseMethod("xml_find_first") 中的错误: 没有适用于“字符”类对象的“xml_find_first”方法

第二选择

MHP_codes <- c(324585, 449807)  #therapist identifier 
withinpage_codes <- c(1:20)     #therapist running number 

df_list <- vector(mode = "list",
                  length = length(MHP_codes) * length(withinpage_codes))

j <- 1
for(code1 in withinpage_codes) { 
  for(code2 in MHP_codes) {
    URL <- paste0('https://www.psychologytoday.com/us/therapists/illinois/', code2, '?sid=5d87f874630bd&ref=', code1, '&rec_next=1&tr=NextProf') 
    df_list[[j]] <- getProfile(URL)
    j <- j + 1 
  } 
}

final_df <- rbind.fill(df_list)

这个循环给出了同样的错误信息(请参考上面那个)。

现在,我只想弄清楚为什么循环没有生成数据集。可能有两个问题:首先,循环中的某些东西不起作用(我只在一个现有页面上运行了两个循环,并且没有生成数据集); 其次,当我在一系列链接上运行循环时,其中一些可能会丢失,这会产生错误消息。

【问题讨论】:

  • 对于一个所谓的真正的初学者很好的问题。希望有更多这样的。 +
  • 谢谢!我只是想复制其他人已经完成的类似抓取项目(我有几个参考资料,所以我最终在这里不提了)

标签: r loops web-scraping


【解决方案1】:

考虑几个调整:

  • 调整函数以接收 URL 参数。右 profilescrape 没有在函数的任何地方使用。函数采用在全局环境中分配的任何 URL。

    getProfile <- function(URL) { 
       ...
    }
    
  • 调整函数的结尾以返回所需的对象。如果没有return,R 将返回读取的最后一行。因此,将str(onet_df) 替换为return(onet_df)

  • 将循环中的动态 URL 传递给方法而不调用 function

    URL <- paste0(...) 
    record_profile <- getProfile(URL)
    
  • 在循环之前初始化一个具有指定长度 (2 x 20) 的列表。然后在每次迭代时分配给循环索引,而不是在循环中增长对象,这是内存效率低下的。

    MHP_codes <- c(324585, 449807)  #therapist identifier 
    withinpage_codes <- c(1:20)     #therapist running number 
    
    df_list <- vector(mode = "list",
                      length = length(MHP_codes) * length(withinpade_codes))
    
    j <- 1
    for(code1 in withinpage_codes) { 
        for(code2 in MHP_codes) {
            URL <- paste0('https://www.psychologytoday.com/us/therapists/illinois/', code2, '?sid=5d87f874630bd&ref=', code1, '&rec_next=1&tr=NextProf') 
            df_list[[j]] <- tryCatch(getProfile(URL), 
                                     error = function(e) NULL)
            j <- j + 1 
        } 
    }
    
  • 在循环外调用rbind.fill 将所有数据帧组合在一起

    final_df <- rbind.fill(df_list)
    

话虽如此,考虑一个 apply 系列解决方案,特别是 Map(包装到 mapply)。这样做,您避免了初始化列表和增量变量的簿记,并且您“隐藏”了紧凑语句的循环。

# ALL POSSIBLE PAIRINGS
web_codes_df <- expand.grid(MHP_codes = c(324585, 449807),
                            withinpage_codes = c(1:20))

# MOVE URL ASSIGNMENT INSIDE FUNCTION
getProfile <- function(code1, code2) { 
   URL <- paste0('https://www.psychologytoday.com/us/therapists/illinois/', code2, '?sid=5d87f874630bd&ref=', code1, '&rec_next=1&tr=NextProf')

    # ...same code as before...
}

# ELEMENT-WISE LOOP PASSING PARAMS IN PARALLEL TO FUNCTION
df_list <- Map(function(code1, code2) tryCatch(getProfile(code1, code2), 
                                               error = function(e) NULL),
               code1 = web_codes_df$MHP_codes,
               code2 = web_codes_df$withinpage_codes)

final_df <- rbind.fill(df_list)

【讨论】:

  • 感谢@Parfait 的建议。不过,这两个版本的循环似乎都不起作用。
  • 请转发错误或不希望的结果。 不工作 描述性不是很好。此解决方案假定getProfile() 没有问题。可能页面不可用,您需要包装 tryCatch 或添加 Sys.sleep 以完成处理。
  • 请用整个 R 错误消息编辑您的帖子。我们可以帮助破译。我的猜测通常发生在网络抓取许多页面时是 one 页面不起作用,破坏了一切。我已经编辑包含tryCatch,它将抑制错误并为那些问题页面返回NULL。查看 df_list 对象以查看未处理的项目。
  • 再次强调,建议的解决方案都不起作用。请描述实际发生的情况。有什么错误吗? df_list 没有生成吗?您的帖子表明网络抓取中的错误,而不是我最后遇到的循环。将NULL 更改为print(e)。另外,我刚刚添加了一点关于 R 函数的返回。现在你的函数返回最后一行:str(onet_dt)。调整return(onet_dt)
  • 顺便说一句 - 包括headstr 调用在内的所有控制台输出都不会在函数内运行,除非您使用print。如果使用Map,甚至尝试在for循环或函数中打印code1code2,看看哪个是有问题的URL。
【解决方案2】:

其中一位用户 Parfait 帮助我解决了问题。所以,非常感谢这位用户。 下面我贴出脚本。如果没有准确评论,我深表歉意。

这里是代码。

#Loading packages
library('rvest') #to scrape
library('xml2')  #to handle missing values (it works with html_node, not with html_nodes)
library('plyr')  #to bind together different data sets

#get working directory
getwd()
setwd("~/YOUR OWN FOLDER HERE")

#DEFINE SCRAPING FUNCTION
getProfile <- function(URL) {


          ##NAME
                #Using CSS selectors to name
                nam_html <- html_node(URL,'.contact-name')
                #Converting the name data to text
                nam <- html_text(nam_html)
                #Let's have a look at the rankings
                head(nam)
                #Data-Preprocessing: removing '\n' (for the next informations, I will keep \n, to help 
                #                                   me separate each item within the same type of 
                #                                   information)
                nam<-gsub("\n","",nam)
                head(nam)
                #Convering each info from text to factor
                nam<-as.factor(nam)
                #Let's have a look at the name
                head(nam)
                #If I need to remove blank space do this:
                  #Data-Preprocessing: removing excess spaces
                  #variable<-gsub(" ","",variable)


            ##MODALITIES
                #Using CSS selectors to modality
                mod_html <- html_node(URL,'.attributes-modality .copy-small')
                #Converting the name data to text
                mod <- html_text(mod_html)
                #Let's have a look at the rankings
                head(mod)
                #Convering each info from text to factor
                mod<-as.factor(mod)
                #Let's have a look at the rankings
                head(mod)

                ##Combining all the lists to form a data frame
                onet_df<-data.frame(Name = nam,                                                                                     
                                    Modality = mod)

                return(onet_df)
}

然后,我将这个函数与一些治疗师循环应用。出于说明目的,我取了四个相邻治疗师的 ID,但事先不知道这些 ID 中的每一个是否已被实际分配(这样做是因为我想看看如果循环偶然发现不存在的链接会发生什么)。

j <- 1
MHP_codes <-  c(163805:163808) #therapist identifier
df_list <- vector(mode = "list", length(MHP_codes))
  for(code1 in MHP_codes) {
    URL <- paste0('https://www.psychologytoday.com/us/therapists/illinois/', code1)
    #Reading the HTML code from the website
    URL <- read_html(URL)
    df_list[[j]] <- tryCatch(getProfile(URL), 
                             error = function(e) NULL)
    j <- j + 1
  }

final_df <- rbind.fill(df_list)
save(final_df,file="final_df.Rda")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多