以t.co方式缩短URL

时间:2015-05-08 16:21:56

标签: python api url twitter url-shortener

我必须检索包含某些YouTube视频链接的推文。但是,Twitter使用t.co网址缩短服务来缩短网址,因此,如果用户发送以下链接https://www.youtube.com/watch?v=x6QZn9xiuOE,则推文会显示为https://t.co/bYeHhy9kAU

因此,我无法使用原始网址,但我必须使用缩短的网址运行查询。

如何从原始网址开始获取t.co缩短的网址?

1 个答案:

答案 0 :(得分:1)

我通过在时间轴上发布原始网址,然后阅读缩短版本,最后使用缩短的网址运行查询来解决我的问题。

这是我使用的Python代码:

twitter_api = twitter.Twitter(auth = auth)

# searching for tweets
video_list = ["HdwMY2Fa7G4","FuqLui0_EF8","ZLUSg1_-o4c",
"jvN5OwkwwmE","D2H839E2PIw","94wmdh23JsQ",
"MIXuXnnW4io","9Jo0uk9ewWQ","9eBHdFpmpHs",
"czr4nUEF77s","Q-P9ygH6T20","SWnXj8Nkpic",
"5IgvJ7mEl4c","grZPvHb0yA8","Gwk6FmiAKCo",
"vCub9qk4vTk","PX0qDfYNykc","HLz_4NVSO6c",
"rTB5kwmv9D4","gXwZ3dbIhjw"]

k = 0 # counter
for vid in video_list:
  k += 1
  # settings
  count = 10
  video_url = 'https://www.youtube.com/watch?v='+vid

  # tweet video URL in my timeline
  twitter_api.statuses.update(status = video_url)

  # retrieve shortened URL from my last tweet
  my_account = 'ibbessi'
  args = {'count' : 1}
  timeline = twitter_api.statuses.user_timeline(screen_name = my_account, **args)
  shortened_url = timeline[0]['text']
  print '# ', str(k), '\noriginal URL:', video_url, '\nshortened URL:', shortened_url, '\n'

  # search the shortened URL
  search_results = twitter_api.search.tweets(q = shortened_url, count = count)
  statuses = search_results['statuses']

  # output shortened URL
  print 'I have found ' + str(len(statuses)) + ' tweet(s) with video ' + shortened_url + '\n'
  for i in range(0,len(statuses)):
      print '#', str(i+1), '\nTEXT: ' , statuses[i]['text'], '\nUSER: ', statuses[i]['user']['name'], '\nRT COUNT: ', statuses[i]['retweet_count'], '\nDATE: ', statuses[i]['created_at'],'\n'
相关问题