开发者社区> 问答> 正文

从R中的网页中提取所有可能的文本

我使用此脚本从网页中提取文本

url <- "http://www.dlink.com/it/it"

doc <- getURL(url)

#get the text from the body
html <- htmlTreeParse(doc, useInternal = TRUE)
txt <- xpathApply(html, "//body//text()[not(ancestor::script)][not(ancestor::style)][not(ancestor::noscript)]", xmlValue)
txt<-toString(txt)

但是问题在于它仅使用首页中的文字,如何将其扩展到整个网站?

展开
收起
游客ufivfoddcd53c 2020-01-04 14:22:33 962 0
1 条回答
写回答
取消 提交回答
  • 我会去rvest梳理链接并purrr进行迭代:

    library(rvest)
    library(purrr)
    
    url <- "http://www.dlink.com/it/it"
    
    r <- read_html(url) %>% 
        html_nodes('a') %>% 
        html_attr('href') %>% 
        Filter(function(f) !is.na(f) & !grepl(x = f, pattern = '#|facebook|linkedin|twitter|youtube'), .) %>% 
        map(~{
            print(.x)
            html_session(url) %>% 
                jump_to(.x) %>% 
                read_html() %>% 
                html_nodes('body') %>% 
                html_text() %>% 
                toString()
        })
    
    

    我从链接列表中过滤掉了社交网络和无效链接,可能还需要进行一些调整。

    建议您将浪费很多垃圾。可能还需要针对每个页面中要擦除的内容进行定位(例如:比整个body标签更具体的内容)

    2020-01-06 10:37:55
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
营销设计场景下的图像和文字生成 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载