首页 > 解决方案 > 网络抓取同义词

问题描述

我正在尝试从 National Cancer Institute Thesaurus 数据库中抓取同义词,但是我在找到正确的 html 来指向这一点时遇到了一些麻烦。下面是我的代码和我正在使用的数据框。当我运行我的脚本来提取同义词时,Error in open.connection(x, "rb") : HTTP error 404.我似乎无法弄清楚正确的 html 链接应该是什么以及如何找到它。

在此处输入图像描述

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

synonyms<-read_csv("terms.csv")
##list of acronyms 
words <- c(synonyms$Keyword)

##Designate html like and the values to search 
htmls <- paste0("https://ncit.nci.nih.gov/ncitbrowser/pages/concept_details.jsf/", words)

Data<-data.frame(Pages=c(htmls))


results<-sapply(Data$Pages, function(url){
  try(
    url %>%
      as.character() %>% 
      read_html() %>% 
      html_nodes('p') %>% 
      html_text()
  )
})

标签: rweb-scrapingpurrrrvest

解决方案


我怀疑这行代码有问题:

##Designate html like and the values to search 
htmls <- paste0("https://ncit.nci.nih.gov/ncitbrowser/pages/concept_details.jsf/", words)

因为paste0() 只是将文本连接在一起,这会给你像这样的 URL

https://ncit.nci.nih.gov/ncitbrowser/pages/concept_details.jsf/Ketamine
https://ncit.nci.nih.gov/ncitbrowser/pages/concept_details.jsf/Azacitidine
https://ncit.nci.nih.gov/ncitbrowser/pages/concept_details.jsf/Axicabtagene+Ciloleucel

虽然我没有特别的经验rvest,但您看到的 404 错误几乎肯定与 Web 浏览器无法加载这些 URL 有关。我建议您登录或打印出来,htmls这样您就可以确认它们确实在 Web 浏览器中正常工作。

我要指出,在这种特殊情况下,该网站提供了一个可下载的数据库;您可能会发现离线下载和查询比进行网络抓取更容易。


推荐阅读