2017-02-02 9 views
0

私はこの単純なプログラムを書いて、特定のユーザーのつぶやきからリンクを抽出しました。私はつぶやきの中にあるリンクを抽出することができましたが、私が得意とするのは、t.coをドメインとして短縮したリンクのようです。これらのリンクは他のつぶやきにつながっています。Pythonのつぶやきから外部リンクを抽出する

問題は、これらのリンクが他のつぶやきにつながることがあることです。つぶやきからリンクを取得する方法と、これらのリンクがTwitterサイト自体ではなく外部サイト用であることを確認する方法。

これは私がそれを記述するのに最良の方法であるため、私の質問がはっきりしていることを願っています。ここで

おかげ

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 

import sys 
import re 

#http://www.tweepy.org/ 
import tweepy 

#Get your Twitter API credentials and enter them here 
consumer_key = "" 
consumer_secret = "" 
access_key = "" 
access_secret = "" 

#method to get a user's last 200 tweets 
def get_tweets(username): 

     #http://tweepy.readthedocs.org/en/v3.1.0/getting_started.html#api 
     auth = tweepy.OAuthHandler(consumer_key, consumer_secret) 
     auth.set_access_token(access_key, access_secret) 
     api = tweepy.API(auth) 

     #set count to however many tweets you want; twitter only allows 200 at once 
     number_of_tweets = 200 

     #get tweets 
     tweets = api.user_timeline(screen_name = username,count = number_of_tweets) 

     for tweet in tweets: 
       urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[[email protected]&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', tweet.text) 
       for url in urls: 
         print url 


#if we're running this as a script 
if __name__ == '__main__': 

    #get tweets for username passed at command line 
    if len(sys.argv) == 2: 
     get_tweets(sys.argv[1]) 
    else: 
     print "Error: enter one username" 

    #alternative method: loop through multiple users 
     # users = ['user1','user2'] 

     # for user in users: 
#  get_tweets(user) 

出力サンプルです:(それはリンクを短くしているので、私はそれを投稿できませんでし)。編集者は私に許可しませんでした。

答えて

0

リダイレクトされたURLを取得する必要があります。私がテストしたツイートの一部が無効なURLを抽出したので、私はtry..exceptブロックを持っている

for tweet in tweets: 
    urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[[email protected]&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', tweet.text) 
    for url in urls: 
     try: 
      res = urllib2.urlopen(url) 
      actual_url = res.geturl() 
      print actual_url 
     except: 
      print url 

:まず、次のコードを試し、その後import urllib2を追加します。

関連する問題