我正在学习数据抓取,最重要的是,我是 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”的方法应用于“character”类的对象
第二种选择
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)
此循环给出了相同的错误消息(请参阅上面的错误消息)。
现在,我只想弄清楚为什么循环没有生成数据集。可能有两个问题:第一,循环中的某些内容不起作用(我只在一个现有页面上运行了两个循环,并且没有生成数据集); 第二,当我在一系列链接上运行循环时,其中一些链接可能会丢失,这会产生错误消息。
最佳答案
考虑一些调整:
调整函数以接收 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
(maply
的包装器)。这样做,您可以避免初始化列表和增量变量的簿记,并“隐藏”紧凑语句的循环。
# 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)
关于r - 使用 R 进行网页抓取和循环浏览页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58054707/