用R-硒刮擦时将NA插入空白值

问题描述

我正在尝试使用RSelenium刮一个网站。通常,我要抓取页面上的10个元素,但有时会丢失其中的一些元素,这些元素会返回5、6或7而不是10的列表。例如:

此代码返回页面上的列表6(缺少四个元素)

`webElems_title2 <- remDr$findElements(using = "xpath",value = "//div[property='title']`")

此代码在同一页面上返回10个列表:(所有10个元素均被删除)

webElems_doc_title <- remDr$findElements(using = "xpath",value = "//a[@class = 'doc-title']")
                                  

我的问题:如果不存在特定元素,如何创建一个插入NA的if语句?我的最终目标是上述两个代码都返回10的列表。

受此帖子启发:Inserting NA in blank values from web scraping。我尝试做类似的事情:

webElems_title2 <- remDr$findElements(using = "xpath",value = "//div[@property = 'title']") %>% replace(!nzchar(.),NA)

受此帖子启发:Inputting NA where there are missing values when scraping with rvest我已经尝试过类似的事情:

webElems_title2 <- remDr$findElements(using = "xpath",value = "//div[@property = 'title']") %>% {if(length(.) == 0) NA else .}

但是它似乎不起作用。我希望有人能帮助我。

解决方法

您可以使用tryCatch函数。

下面是可能的解决方案:

Your scrape code...

#The variable webElems_title2 
tryCatch(expr ={
#scrapes information of 'webElems_title2 '
webElems_title2 <- remDr$findElements(using = "xpath",value = "//div[@property = 'title']")$getElementAttribute('value')
},#If the information does not exist in this way you write NA to the webElems_title2 element
error = function(e){          
webElems_title2 <-NA
})

Your scrape code...

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...