【问题标题】:for loop to check if list of xpaths exists in Rfor循环检查R中是否存在xpath列表
【发布时间】:2019-09-02 11:45:21
【问题描述】:

我有一个 html_nodes 列表,我想检查它们是否存在于页面中,如果存在则返回 1,如果不存在则返回 0。

我已经手动尝试了每个节点的“if”功能,但由于它们可能会随着时间而改变,我需要从整个网站上抓取所有可用节点并检查每个页面上的每个节点。

我有什么

data<-foreach(i=urls) %dopar% {
node1 <- read_html(i) %>% html_nodes(xpath = node1) %>%  html_text()
if (length(node1)>0){
node1<-1
} else{
node1<-0
}
node2 <- read_html(i) %>% html_nodes(xpath = node2) %>%  html_text()
if (length(node1)>0){
node2<-1
} else{
node2<-0
}
}

我需要类似的东西(直觉):

data<-foreach(i=urls) %dopar% {
for (j in nodes) {  
node <- read_html(i) %>% html_nodes(xpath = j) %>%  html_text()
if (length(node)>0){
node<-1
} else{
node<-0
}
}
}

【问题讨论】:

    标签: r for-loop xpath web-scraping parallel.foreach


    【解决方案1】:

    您快到了,您的节点确实需要一个循环。 sapply 和 co 是你的朋友:

    data <- foreach(i=urls) %dopar% {
       sapply(nodes, function(j)  
           length(read_html(i) %>% html_nodes(xpath = j) %>%  html_text()) > 0)
    }
    

    【讨论】:

      猜你喜欢
      • 2017-10-17
      • 2020-08-09
      • 2017-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-12
      相关资源
      最近更新 更多