You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Twitter数据情感分析遇get_oauth_sig错误:OAuth未注册会话的解决方法

解决Twitter API OAuth认证错误:OAuth has not been registered for this session

我最近在用Twitter数据做情感分析,跑代码的时候碰到了这个头疼的错误:Error in get_oauth_sig() : OAuth has not been registered for this session,具体的代码执行步骤如下:

# 最初的oauth端点定义(注意这里有拼写错误)
oauth_endpoint(authorize = "https://api.twitter.com/oauth", access= "https://api.twitter.com/oauth/access_tocken" )

# 下载证书文件
download.file(url=' http://curl.haxx.se/ca/cacert.pem ', destfile='cacert.pem')
# 输出信息:
# trying URL ' http://curl.haxx.se/ca/cacert.pem '
# Content type 'application/x-pem-file' length 236061 bytes (230 KB)
# downloaded 230 KB

# 重新定义OAuth相关URL
reqURL <- 'https://api.twitter.com/oauth/request_token'
accessURL <- 'https://api.twitter.com/oauth/access_token'
authURL <- 'https://api.twitter.com/oauth/authorize'

# 填写密钥信息
consumerKey <- 'key used'
consumerSecret <- 'key used'
accesstoken <- 'key used'
accesssecret <- 'key used'

# 创建OAuth凭据对象
Cred = OAuthFactory$new(consumerKey=consumerKey,
                        consumerSecret=consumerSecret,
                        requestURL=reqURL,
                        accessURL=accessURL,
                        authURL=authURL)

# 完成握手流程
Cred$handshake(cainfo= system.file('CurlSSL', 'cacert.pem', package = 'RCurl'))
# 输出提示:
# To enable the connection, please direct your web browser to:
# https://api.twitter.com/oauth/authorize?oauth_token=0AflNwAAAAAA4AHwAAABYOpNKOk
# When complete, record the PIN given to you and provide it here: 9642678

# 保存凭据
save(Cred, file = 'twitter authentication.Rdata')

# 调用搜索接口时出错
some_tweets = searchTwitter("trump", n=2000, lang = "en")
# 错误信息:Error in get_oauth_sig() : OAuth has not been registered for this session

问题原因&解决办法

别担心,这个错误的核心是你生成的OAuth凭据(Cred对象)没有在当前R会话中注册生效,下面给你几个实用的解决步骤:

  • 步骤1:手动注册OAuth凭据
    在调用searchTwitter()之前,一定要加上这行代码,把你的凭据注册到会话中:

    registerOAuth(Cred)
    

    这一步会告诉R:接下来的Twitter API调用要用这个Cred对象来做认证。

  • 步骤2:重启会话后重新加载凭据
    如果你是重启了R之后再跑的代码,记得先加载之前保存的认证文件,再注册:

    load('twitter authentication.Rdata')  # 加载保存的Cred对象
    registerOAuth(Cred)                   # 注册到当前会话
    

    因为每次重启R,之前的变量都会被清空,必须重新加载并注册凭据。

  • 步骤3:修正拼写错误
    我注意到你最初定义oauth_endpoint时,把access_token拼成了access_tocken(少了一个e),虽然你后面重新定义了accessURL,但这个拼写错误可能会影响后续的认证流程,建议修正这个地方,避免其他潜在问题。

验证方法

执行完上面的步骤后,你可以先跑一个小测试:

test_tweets = searchTwitter("test", n=10, lang="en")

如果能正常返回数据,就说明认证已经成功了,接下来就可以放心跑你的情感分析代码啦!

内容的提问来源于stack exchange,提问作者santhosh kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:02:48