我使用 sqlite3 存盤來自熊貓資料幀的資料
我從 Twitter 抓取資料,我希望它每小時一次
為此,我想過濾資料庫中的日期,日期格式如下:
2021-11-11 08:07:33 00:00
我使用的查詢:
cur.execute("SELECT * FROM tweets_b_db WHERE tweet_created_at > " li " ")
li 是一個變數,在再次填充資料庫之前最后插入的日期
cur.execute("SELECT tweet_created_at FROM tweets_b_db ORDER BY tweet_created_at DESC LIMIT 1")
li = cur.fetchone()
它回傳什么:
can only concatenate str (not "tuple") to str
我的代碼:
import tweepy
import time
import datetime
import pandas as pd
import sqlite3
con = sqlite3.connect('tweetScaping.db')
cur = con.cursor()
consumer_key = "**********************"
consumer_secret = "****"
access_token = "****-*****"
access_token_secret = "***************"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True)
# using tweepy to search for the keyword Bouygues telecom
text_query = 'bouygues telecom OR @bouyguestelecom OR #Bouygues'
count = 200
try:
# Creation of query method using parameters
tweets = tweepy.Cursor(api.search_tweets, q=text_query " -filter:retweets").items(count)
# Pulling information from tweets iterable object
tweets_list = [[tweet.created_at, tweet.id, tweet.text] for tweet in tweets]
# Creation of dataframe from tweets list
# Add or remove columns as you remove tweet information
# tweets_df = pd.DataFrame(columns=['tweet_created_at', 'tweet_id', 'tweet_text'])
tweets_df = pd.DataFrame(tweets_list)
tweets_df.columns = ['tweet_created_at', 'tweet_id', 'tweet_text']
#last inserted
cur.execute("SELECT tweet_created_at FROM tweets_b_db ORDER BY tweet_created_at DESC LIMIT 1")
li = cur.fetchone()
# to insert results to database (sqlite3)
tweets_df.to_sql(name='tweets_b_db', con=con, if_exists='replace')
# to show table content
cur.execute("SELECT * FROM tweets_b_db WHERE tweet_created_at > " li " ")
print(cur.fetchall())
except BaseException as e:
print('failed on_status,', str(e))
time.sleep(3)
更新:使用:
cur.execute("SELECT tweet_created_at FROM tweets_b_db ORDER BY tweet_created_at DESC LIMIT 1")
data = cur.fetchone()
data = data[0]
cur.execute("SELECT * FROM tweets_b_db WHERE tweet_created_at >= Datetime('{data}')")
print(cur.fetchall())
不回傳任何內容:
[]
如果有人能引導我走向正確的方向,那將非常有幫助
uj5u.com熱心網友回復:
fetchone() 回傳一個元組,其中包含您在查詢中請求的所有列。在您的情況下,只有一列 (tweet_created_at),因此您的元組中將出現一個元素(tweet_created_at 的值),可以在索引 0 處訪問該元素。
li = cur.fetchone()
li = li[0]
uj5u.com熱心網友回復:
如果對 sql 陳述句使用 f 字串:
cur.execute(f"SELECT * FROM tweets_b_db WHERE tweet_created_at >= Datetime('{data}')")
我相信你的代碼會起作用。
但是,推薦的引數傳遞方式是使用?占位符:
cur.execute("SELECT * FROM tweets_b_db WHERE tweet_created_at >= Datetime(?)", (data,))
此外,如果data日期時間格式正確,則yyyy-mm-dd hh:MM:ss不需要該功能DATETIME():
cur.execute("SELECT * FROM tweets_b_db WHERE tweet_created_at >= ?", (data,))
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/360108.html
