2017-08-20 28 views
1

urlsが正しく定義されていますが、私は"global name 'urls' is not defined"を取得し続け、URLデータはMYSQLinsertedではありません。どこの提案?私はここで間違いをしているのですか?Pythonグローバル名 'urls'が定義されていません。

# ! /usr/bin/python 

# Description : This script can collect the URLs from Tweets and Records them into research MYSQL DB. 

from __future__ import print_function 
import tweepy 
import json 
import MySQLdb 
from dateutil import parser 

WORDS = ['security'] 

# CREDENTAILS 
CONSUMER_KEY = "" 
CONSUMER_SECRET = "" 
ACCESS_TOKEN = "" 
ACCESS_TOKEN_SECRET = "" 

HOST = "192.168.150.94" 
USER = "root" 
PASSWD = "blah" 
DATABASE = "tweets" 


def store_data(tweet_url): 
    db = MySQLdb.connect(host=HOST, user=USER, passwd=PASSWD, db=DATABASE, 
         charset="utf8") 
    cursor = db.cursor() 
    insert_query = "INSERT INTO tweet_url (urls) VALUES (%s)" 
    cursor.execute(insert_query, (urls)) 
    db.commit() 
    cursor.close() 
    db.close() 
    return 


class StreamListener(tweepy.StreamListener): 
    def on_connect(self): 
     print("We are now connected to the streaming API.") 

    def on_error(self, status_code): 
     print('An Error has occured: ' + repr(status_code)) 
     return False 

    def on_data(self, data): 
     try: 
      datajson = json.loads(data) 
      web_url = datajson['entities']['urls'] 
      print(web_url) 
      for i in web_url: 
       web_urls = i['expanded_url'] 
       urls = web_urls 
      print(urls) 
     store_data(urls) 

    except Exception as e: 
    print(e) 


auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) 
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) 
listener = StreamListener(api=tweepy.API(wait_on_rate_limit=True)) 
streamer = tweepy.Stream(auth=auth, listener=listener) 
print("Tracking: " + str(WORDS)) 
streamer.filter(track=WORDS) 
+1

'web_url'が空で' urls'が存在しないのではないでしょうか? –

答えて

1

あなたはちょうどあなたがデータを保存する方法が不明のまま

def store_data(tweet_url): 
    db = MySQLdb.connect(host=HOST, user=USER, passwd=PASSWD, db=DATABASE, 
         charset="utf8") 
    cursor = db.cursor() 
    insert_query = "INSERT INTO tweet_url (urls) VALUES (%s)" 
    cursor.execute(insert_query, (tweet_url)) 

tweet_url

に機能 store_dataのパラメータ urlsの名前を変更する必要があります。あなたはループの後 store_dataを呼び出した場合、あなたがより良いリスト内の各値を格納する必要があり、最後の値を格納しています:

def on_data(self, data): 
    try: 
     datajson = json.loads(data) 
     web_url = datajson['entities']['urls'] 
     print(web_url) 
     urls = [] 
     for i in web_url: 
      urls.append((i['expanded_url'],)) 
      # stores a tuple to make it easy in the database insertion 
     print(urls) 
     store_data(urls) 
    except: 
     [...] 

この道をstore_data内部に別の少しの修正が必要になります。

あなたのインサイド
def store_data(urls): 
    db = MySQLdb.connect(host=HOST, user=USER, passwd=PASSWD, db=DATABASE, 
         charset="utf8") 
    cursor = db.cursor() 
    insert_query = "INSERT INTO tweet_url (urls) VALUES (%s)" 
    cursor.executemany(insert_query, urls) 
    db.commit() 
    cursor.close() 
    db.close() 
    return 
+0

ありがとうMoureu、それを変更しました!うまく動作します – Arun

+0

PRmonreu:しかしここには終わりがあります。ツイート "web_url"に2つ以上のURLがあると、 "文字列フォーマット中にすべての引数が変換されません"というエラーが発生します。しかし、ツイートにURLが1つしかない場合は、それがMYSQLに挿入されています。 ? – Arun

+0

@Arun何が間違っているのかを理解するために、この[post](https://stackoverflow.com/questions/14011160/how-to-use-python-mysqldb-to-insert-many-rows-at-once)をチェックし、 'store_data()'では、 'urls'はタプルのリスト(内部に' expanded_url'を1つ含む)である必要があります。 'executemany'はこのリストを繰り返します。 – PRMoureu

1

関数store_data()あなたは関数に渡すものがtweet_urlなので、定義されていないurlsを使用しています。

def store_data(urls): 
    # ... 

またはあなたの関数本体でtweet_urlurlsを変更します:

# ... 
cursor.execute(insert_query, (tweet_url)) 
# ... 

そして、あなたが修正を確認してくださいあなたはurlsの代わりに、このようなtweet_urlにあなたの関数の引数を変更するか必要

内側のくぼみon_data()方法:

class StreamListener(tweepy.StreamListener): 
    # ... 

    def on_data(self, data): 
     try: 
      datajson = json.loads(data) 
      web_url = datajson['entities']['urls'] 
      print(web_url) 
      for i in web_url: 
       web_urls = i['expanded_url'] 
       urls = web_urls 
      print(urls) 
      store_data(urls) 
     except Exception as e: 
      print(e) 
+0

ああスナップ!ごめんなさい !ありがとう:) – Arun

関連する問題