2014-04-08 47 views
1

我有一個使用「gdshortener」模塊生產我的源URL縮短版的一些代碼:字符串轉換不生產所需的值

import simplejson 
import httplib2 
import twitter 
import gdshortener 
from random import randint 

print("Python will now attempt to submit tweets to twitter...") 


try: 

    api = twitter.Api(consumer_key='', 
         consumer_secret='', 
         access_token_key='', 
         access_token_secret='') 

    b = 0 

    for a in range(0, 1): #only range 0-1 for this question, actually 1-21 
     b = b + 1 
     a = randint(1,60000000) 
     randint 
     print ("a = ", a) 
     aa = str(a) 


     s1 = gdshortener.ISGDShortener() 
     print s1.shorten(url = 'http://audiotechracy.blogspot.co.uk/2014/03/reviewing-synapse-antidote-rack.html', custom_url = aa) 
     ss1 = str(s1) 

     status = api.PostUpdate("The new Synapse Antidote Rack Extension:" + ss1 + " #propellerhead #synapse") 



    print("Tweets submitted successfully!") 

except Exception,e: 
    print str(e)  
    print("Twitter submissions have failed!!!") 

我使用的是隨機數發生器來產生六位數然後將這些數字提供給此模塊的custom_url參數。這很好,我得到了一系列僞隨機數。但是,當我試着連接我的推特字符串,我的動態短網址和一些井號標籤時,我收到一個錯誤,我無法連接字符串和整數值。

所以我然後創建的變量「SS1」,這是「S1」的字符串,但是這現在產生這樣的鳴叫:

The new Synapse Antidote Rack Extension:<gdshortener.gdshortener.ISGDShortener object at 0x000000000542AA20> #propellerhead #synapse 

我怎樣才能得到它,這樣產生的鳴叫是:

The new Synapse Antidote Rack Extension: http://is.gd/58077181 #propellerhead #synapse 

感謝

+0

'ISGDShortener()'方法不會返回可以簡單地轉換爲字符串的對象。您可以查看API文檔或鍵入'dir(s1)'並查看當前正在使用的對象的屬性/方法。 – Matthew

回答

3

經過模塊,發現它返回一個元組。請參閱以下內容以提取正確的URL。

代碼:

import gdshortener 

s1 = gdshortener.ISGDShortener() 
x1 = s1.shorten(url='http://audiotechracy.blogspot.co.uk/2014/03/reviewing-synapse-antidote-rack.html')[0] 
print x1 

結果:

http://is.gd/KKxmFd 
[Finished in 0.8s] 

注意我是如何在shorten的末尾添加一個[0]。這是因爲shorten返回一個元組,我們可以索引類似於列表。

希望這會有所幫助。

+0

除此之外,你(user3045351)試圖打印對象's1'而不是'shorten'方法的結果。 – Matthew

+0

@胡曼是對的。這有點像試圖打印一個函數或一個生成器,而不是它們的結果。 :) – Manhattan

+0

@ nanshi是的,我認爲有些東西與我編碼的方式看起來不正確。謝謝你的幫助。我現在唯一的問題是'http://is.gd/'鏈接格式觸發twitter的警告,即上述擴展通常用於垃圾郵件或網絡釣魚廣告系列。我迄今還沒有找到一個標準的網址縮短者,儘管誰通過他們的api提供了一個可定製的網址選項。 – gdogg371

相關問題