首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用R对网页进行抓取和循环

用R对网页进行抓取和循环
EN

Stack Overflow用户
提问于 2019-09-23 01:32:45
回答 2查看 1.6K关注 0票数 4

我正在学习数据抓取,最重要的是,我非常喜欢R(对于工作,我使用STATA,我只对非常具体的任务使用R)。为了学习刮擦,我正在练习几页“今日心理学”。

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

代码语言:javascript
复制
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)

这段代码似乎对我选择的任何治疗师都很有效。现在,我想在多个配置文件上使用这个函数来生成一个数据集,其中包含MHPs的名称和方式。假设我想将上面的函数"getProfile“应用于伊利诺伊州的前20名治疗师,并将这20名治疗师的信息输入到一个名为"onet_df”的数据集中。

代码语言:javascript
复制
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
      }
}

编辑从这里开始:

这个循环不会创建任何数据集;而且,它也不会给出任何错误消息。有人能帮我排除这个循环的缺陷吗?请记住,我是一个真正的初学者。

在提出以下建议后,我首先修改了以下内容:

代码语言:javascript
复制
#creating the function
getProfile <- function(URL) {....}

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

第一选择

代码语言:javascript
复制
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”方法

第二代

代码语言:javascript
复制
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)

此循环提供相同的错误消息(请参阅上面的错误消息)。

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-09-23 03:07:02

考虑几项调整:

  • 调整函数以接收URL参数。正确的轮廓在功能上不被使用。函数接受全局环境中分配的任何URL。

getProfile <- (URL){.}

  • 调整函数的结尾以返回所需的对象。如果没有return,R将返回最后一行读。因此,在循环到方法中用return(onet_df).

  • Pass动态URL替换str(onet_df),而不调用function

URL <- paste0(.)getProfile(URL)

  • Initialize循环前具有指定长度(2x20)的列表。然后在每次迭代中分配给循环索引,而不是在循环中增长对象,这是内存效率低下。

MHP_codes <- c(324585,449807) #治疗师标识符withinpage_codes <- c(1:20) #治疗师运行编号df_list <-向量(mode= "list",长度=长度( MHP_codes) *长度(Withinpade_codes))j <- 1用于(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),getProfile= function(e) NULL) j <- j+1}

  • 调用rbind.fill一次,将所有数据帧组合在一起。

rbind.fill(df_list) <- final_df

尽管如此,考虑一个应用系列解决方案,特别是Map (mapply的包装器)。这样做,您就避免了初始化list和增量变量的簿记,并且“隐藏”了用于Compact语句的循环。

代码语言:javascript
复制
# 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)
票数 2
EN

Stack Overflow用户

发布于 2019-09-24 20:44:58

其中一个用户Parfait帮助我解决了这些问题。所以,非常感谢这个用户。下面我发布了脚本。如果不是预先评论的话,我很抱歉。

这是密码。

代码语言:javascript
复制
#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都被分配了(这是因为我想看看如果循环在一个不存在的链接上绊倒了会发生什么)。

代码语言:javascript
复制
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")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58054707

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档