【问题标题】:How do you subset data from a list in R?你如何从 R 中的列表中子集数据?
【发布时间】:2021-10-04 16:21:12
【问题描述】:

我想从最后一行代码生成的所有 16 个页面中提取职位描述,也就是“p”标签 HTML 元素。

“ret”是由最后一行代码生成的 16 个 HTML 页面的列表。我不习惯使用列表列表,所以我很困惑如何从这些列表中提取数据。

通常我会使用

res %>%
html_elements("body p")

但我收到错误消息“UseMethod("xml_find_all") 中的错误: 'xml_find_all' 没有适用的方法应用于“list”类的对象

library(tidyverse)
library(rvest)
library(xml2)

url<-"https://www.indeed.com/jobs?q=data%20analyst&l=San%20Francisco%2C%20CA&vjk=0c2a6008b4969776"
page<-xml2::read_html(url)#function will read in the code from the webpage and break it down into different elements (<div>, <span>, <p>, etc.

#get job title
title<-page %>%
  html_nodes(".jobTitle") %>%
  html_text()
  
#get company Location
loc<-page %>%
  html_nodes(".companyLocation") %>%
  html_text()

#job snippet
page %>%
  html_nodes(".job-snippet") %>%
  html_text()

#Get link 
desc<- page %>%
  html_nodes("a[data-jk]") %>%
  html_attr("href") 

# Create combine link 
combined_link <- paste("https://www.indeed.com", desc, sep="")

#Turn combined link into a session follow link



page1 <-  html_session(combined_link[[1]])
page1 %>%
  html_nodes(".iCIMS_JobContent, #jobDescriptionText") %>%
  html_text()

#one<- page %>% html_elements("a[id*='job']")

#create function return a list of page-returns

ret <- lapply(paste0("https://www.indeed.com", desc), read_html)

  

【问题讨论】:

  • 你需要purrr::map(ret[1:2], ~ .x %&gt;% html_nodes(".iCIMS_JobContent, #jobDescriptionText") %&gt;% html_text())
  • 这是完美的。请解释代码的“purrr::map(ret[1:2], ~ .x”部分是如何工作的。非常感谢!!!完美运行
  • 谢谢,我发布了一个带有解释的解决方案。谢谢

标签: r list web-scraping subset


【解决方案1】:

我们可以使用lapplybase R

out <- lapply(ret, function(x) x %>%
         html_nodes(".iCIMS_JobContent, #jobDescriptionText") %>% 
          html_text())

或循环使用来自purrrmap

library(purrr)
out <- map(ret, ~ .x %>% 
         html_nodes(".iCIMS_JobContent, #jobDescriptionText") %>% 
         html_text())

注意:两者都在循环 list 的元素,.xx 是单个元素(来自匿名函数 - 即动态创建的函数(function(x)~ - 在tidyverse)

【讨论】:

    猜你喜欢
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 2012-03-26
    • 2012-11-18
    • 2020-12-29
    • 2015-10-04
    相关资源
    最近更新 更多