缩短的URL需要随机化

2024-05-29 10:29:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的代码,这是几乎正常工作。三个网址被缩短,然后放入三个不同tweet的内容中,然后提交给twitter。但是,每次缩短URL时,缩短的URL都是相同的。正因为如此,twitter垃圾邮件过滤器一直在捕捉tweets

有没有一种方法可以随机显示缩短的url来阻止这种情况的发生,或者使用import tinyurl,或者完全使用其他方法

import simplejson
import httplib2
import twitter
import tinyurl

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

try:

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

    for u in tinyurl.create('http://audiotechracy.blogspot.co.uk/2014/03/reviewing-synapse-antidote-rack.html',
                        'http://audiotechracy.blogspot.co.uk/2014/03/free-guitar-patches-for-propellerhead.html',
                        'http://audiotechracy.blogspot.co.uk/2014/02/get-free-propellerhead-rock-and-metal.html',
                        ):
        print u
        linkvar1 = u
        linkvar2 = u
        linkvar3 = u

    status = api.PostUpdate("The new Synapse Antidote Rack Extension:" + linkvar1 + " #propellerhead #synapse")
    status = api.PostUpdate("Free Propellerhead guitar patches for everyone!" + linkvar2 + " #propellerhead #reason #guitar")
    status = api.PostUpdate("Free Metal and Rock drum samples!" + linkvar3 + " #propellerhead #reason)


    print("Tweets submitted successfully!")

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

谢谢


Tags: importapihttpforhtmlstatustwitterprint
1条回答
网友
1楼 · 发布于 2024-05-29 10:29:01

当循环遍历tinyurl.create的结果时,每次都将它赋给所有三个linkvar变量,因此当循环结束时,所有三个变量都将等于u的最后一个值

如果总是要处理相同数量的URL,则可以将它们显式地分配给变量:

linkvar1, linkvar2, linkvar3 = tinyurl.create(
    'http://audiotechracy.blogspot.co.uk/2014/03/reviewing-synapse-antidote-rack.html',
    'http://audiotechracy.blogspot.co.uk/2014/03/free-guitar-patches-for-propellerhead.html',
    'http://audiotechracy.blogspot.co.uk/2014/02/get-free-propellerhead-rock-and-metal.html',
)

如果URL的数量可能会改变,那么最好使用list并为所需结果编制索引:

linkvars = tinyurl.create(
    'http://audiotechracy.blogspot.co.uk/2014/03/reviewing-synapse-antidote-rack.html',
    'http://audiotechracy.blogspot.co.uk/2014/03/free-guitar-patches-for-propellerhead.html',
    'http://audiotechracy.blogspot.co.uk/2014/02/get-free-propellerhead-rock-and-metal.html',
)
status = api.PostUpdate("The new Synapse Antidote Rack Extension:" + linkvars[0] + " #propellerhead #synapse")
status = api.PostUpdate("Free Propellerhead guitar patches for everyone!" + linkvars[1] + " #propellerhead #reason #guitar")
...

相关问题 更多 >

    热门问题