【发布时间】:2014-10-09 14:01:04
【问题描述】:
我想知道是否有更有效的方法来实现我的目标。我目前正在编写一个蜘蛛算法来每天早上获取新闻报道,我想过滤首页的初始链接以忽略我不关心的内容。
您可以使用以下代码生成可重现的示例:
library(RCurl)
library(XML)
opts = list(
proxy = "***.***.***.***", #insert your proxy
proxyusername = "domain\\username",
proxypassword = "password",
proxyport = ****) #insert your port number
links <- 'http://www.cnn.com'
xpaths <- c('//ul[@id="us-menu"]//a', '//div[@id="cnn_maint1lftf"]//a', '//div[@id="cnn_maintt2bul"]//a', '//div[@id="cnn_maintoplive"]//a')
response <- getURL('www.cnn.com', .opts=opts)
doc <- htmlParse(response)
for (xpath in xpaths) {
li <- getNodeSet(doc, xpath)
links <- c(links, sapply(li, xmlGetAttr, 'href'))
}
links <- links[!duplicated(links)]
links <- links[-1]
这是我希望提高效率的代码:
bad.words <- c('video', 'travel', 'living', 'health', 'ireport', 'bleacher', 'showbiz', 'mcafee')
t.1 <- sapply(links, function(x) sapply(bad.words, function(z) any(length(grep(z, x, ignore.case=T)) > 0)))
t.1 <- unname(t.1)
t.1 <- colSums(t.1)
links <- links[!t.1]
我必须假设有比这更清洁、更有效的方法来实现我的目标。有什么想法吗?
【问题讨论】:
-
您的示例不太可重现。在
getURL()中找不到对象opts -
啊,谢谢@RichardScriven。我已经编辑了问题以纠正这一点。
标签: r performance algorithm