2012-05-31 51 views
4

我創建了一個循環函數,它使用具有特定時間間隔的搜索API(可以說每隔5分鐘)提取推文。此函數執行它假設的操作:連接到Twitter,提取包含特定關鍵字的推文,並將它們保存在csv文件中。但是偶爾(每天2-3次)循環停止,因爲這兩個錯誤之一:循環函數中的循環錯誤(用於從Twitter中提取數據)

  • 錯誤htmlTreeParse(URL,useInternal = TRUE): 錯誤創建解析器http://search.twitter.com/search.atom?q= 6.95322e -310tst & RPP = 100 &頁= 10

  • 錯誤UseMethod( 「xmlNamespaceDefinitions」): 施加到 類 「NULL」 的對象關於 'xmlNamespaceDefinitions' 不適用方法

我希望你能幫助我處理這些錯誤,回答我的一些問題:

  • 是什麼原因導致出現這些錯誤?
  • 如何調整我的代碼以避免這些錯誤?
  • 我該如何強制循環在遇到錯誤時繼續運行(例如使用Try函數)?

我的功能(基於網上找到幾個腳本)如下:

library(XML) # htmlTreeParse 

    twitter.search <- "Keyword" 

    QUERY <- URLencode(twitter.search) 

    # Set time loop (in seconds) 
    d_time = 300 
    number_of_times = 3000 

    for(i in 1:number_of_times){ 

    tweets <- NULL 
    tweet.count <- 0 
    page <- 1 
    read.more <- TRUE 

    while (read.more) 
    { 
    # construct Twitter search URL 
    URL <- paste('http://search.twitter.com/search.atom?q=',QUERY,'&rpp=100&page=', page, sep='') 
    # fetch remote URL and parse 
    XML <- htmlTreeParse(URL, useInternal=TRUE, error = function(...){}) 

    # Extract list of "entry" nodes 
    entry  <- getNodeSet(XML, "//entry") 

    read.more <- (length(entry) > 0) 
    if (read.more) 
    { 
    for (i in 1:length(entry)) 
    { 
    subdoc  <- xmlDoc(entry[[i]]) # put entry in separate object to manipulate 

    published <- unlist(xpathApply(subdoc, "//published", xmlValue)) 

    published <- gsub("Z"," ", gsub("T"," ",published)) 

    # Convert from GMT to central time 
    time.gmt <- as.POSIXct(published,"GMT") 
    local.time <- format(time.gmt, tz="Europe/Amsterdam") 

    title <- unlist(xpathApply(subdoc, "//title", xmlValue)) 

    author <- unlist(xpathApply(subdoc, "//author/name", xmlValue)) 

    tweet <- paste(local.time, " @", author, ": ", title, sep="") 

    entry.frame <- data.frame(tweet, author, local.time, stringsAsFactors=FALSE) 
    tweet.count <- tweet.count + 1 
    rownames(entry.frame) <- tweet.count 
    tweets <- rbind(tweets, entry.frame) 
    } 
    page <- page + 1 
    read.more <- (page <= 15) # Seems to be 15 page limit 
    } 
    } 

    names(tweets) 

    # top 15 tweeters 
    #sort(table(tweets$author),decreasing=TRUE)[1:15] 

    write.table(tweets, file=paste("Twitts - ", format(Sys.time(), "%a %b %d %H_%M_%S %Y"), ".csv"), sep = ";") 

    Sys.sleep(d_time) 

    } # end if 
+3

'tryCatch'和'try'是什麼你在追求。 –

+0

關於如何實施tryCatch或嘗試的任何建議? – Gert

+1

TryCatch +有用鏈接的示例: http://stackoverflow.com/a/2622930/473899 現在運行您的代碼,但目前爲止還沒有收到任何錯誤,所以我們將看看我是否有任何有用的添加。 – Esteis

回答

0

我的猜測是,您的問題對應的twitter(或者連接到網絡)是向下或慢或什麼,所以得到一個不好的結果。你有沒有試過設置

options(error = recover) 

然後下一次你得到一個錯誤,一個很好的瀏覽器環境會起來讓你有一個捅。

1

這是我的解決方案,使用try來解決Twitter API的類似問題。

我在Twitter用戶的長長名單中詢問Twitter API的每個人的追隨者人數。當用戶保護他們的帳戶時,我會收到一個錯誤,並且在我放入try函數之前,循環會中斷。使用try允許循環繼續工作,跳到列表中的下一個人。

這裏的設置

# load library 
library(twitteR) 
# 
# Search Twitter for your term 
s <- searchTwitter('#rstats', n=1500) 
# convert search results to a data frame 
df <- do.call("rbind", lapply(s, as.data.frame)) 
# extract the usernames 
users <- unique(df$screenName) 
users <- sapply(users, as.character) 
# make a data frame for the loop to work with 
users.df <- data.frame(users = users, 
         followers = "", stringsAsFactors = FALSE) 

這裏與try循環處理錯誤而填充用戶$來自Twitter的API獲得追隨者計數的追隨者

for (i in 1:nrow(users.df)) 
    { 
    # tell the loop to skip a user if their account is protected 
    # or some other error occurs 
    result <- try(getUser(users.df$users[i])$followersCount, silent = TRUE); 
    if(class(result) == "try-error") next; 
    # get the number of followers for each user 
    users.df$followers[i] <- getUser(users.df$users[i])$followersCount 
    # tell the loop to pause for 60 s between iterations to 
    # avoid exceeding the Twitter API request limit 
    print('Sleeping for 60 seconds...') 
    Sys.sleep(60); 
    } 
# 
# Now inspect users.df to see the follower data