首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >选择正确的html元素

选择正确的html元素
EN

Stack Overflow用户
提问于 2022-12-02 19:25:53
回答 1查看 41关注 0票数 0

我的一些激情,一个堆栈用户帮助我制作这个脚本。我编辑它是为了添加更多的属性,但是当我尝试添加作者时,我遇到了问题

作者标签在targethref旁边。这部分我有问题。

代码语言:javascript
运行
复制
 library(tidyverse)
 library(rvest)

 startTime <- Sys.time()
 get_cg <- function(pages) {

   cat("Scraping page", pages, "\n")

   page <-
   str_c("https://cgspace.cgiar.org/discover? 
   scope=10568%2F106146&query=cassava&submit=&rpp=10&page=", pages) %>%
   read_html()


  tibble(
  title = page %>%
  html_elements(".ds-artifact-item") %>%
  html_element(".description-info") %>%
  html_text2(), # run well

  fecha = page %>% 
  html_elements(".ds-artifact-item") %>%
  html_element(".date") %>%
  html_text2(), # run well

  Type = page %>% 
  html_elements(".ds-artifact-item") %>%
  html_element(".artifact-type") %>%
  html_text2(), # run well

  Autor= page %>% 
  html_elements(".ds-artifact-item") %>% 
  html_element(".description-info") %>%
  html_attr("href"), # not download the Authors

  link = page %>%
  html_elements(".ds-artifact-item") %>%
  html_element(".description-info") %>%
  html_attr("href") %>% # run well
  str_c("https://cgspace.cgiar.org", .)
  )
     }

  df <- map_dfr(1, get_cg)

  endTime <- Sys.time()
  print(endTime - startTim)

我尝试与其他选择器,但得到NA

EN

回答 1

Stack Overflow用户

发布于 2022-12-03 10:10:03

在您发布的代码中,您使用html_element提取Autor和链接字段,但是html_element只选择第一个匹配元素。您应该使用html_nodes,它将返回所有匹配的元素。

下面是如何使用html_nodes提取Autor和链接字段:

代码语言:javascript
运行
复制
Autor = page %>%
  html_elements(".ds-artifact-item") %>%
  html_nodes(".description-info") %>%
  html_attr("href"),

link = page %>%
  html_elements(".ds-artifact-item") %>%
  html_nodes(".description-info") %>%
  html_attr("href") %>%
  str_c("https://cgspace.cgiar.org", .)

注意,html_nodes返回一个元素列表,因此需要使用map_chr或其他函数从列表中提取href属性。

例如,您可以这样使用map_chr:

代码语言:javascript
运行
复制
Autor = page %>%
  html_elements(".ds-artifact-item") %>%
  html_nodes(".description-info") %>%
  map_chr("href"),

link = page %>%
  html_elements(".ds-artifact-item") %>%
  html_nodes(".description-info") %>%
  map_chr("href") %>%
  str_c("https://cgspace.cgiar.org", .)

这应该提取所有匹配元素的href属性,并将它们作为字符向量返回。然后,可以使用此向量在数据帧中创建Autor列和链接列。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74660619

复制
相关文章

相似问题

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