我在使用Python方面很新穎,而且我正在尋找將Twitter數據收集到我的MySQL數據庫中的一個項目。我有我的劇本從本教程中收集數據:插入到mysql數據庫而不是打印
import re
from re import sub
import time
import cookielib
from cookielib import CookieJar
import urllib2
from urllib2 import urlopen
import difflib
cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
keyWord = 'nyc'
startingLink = 'https://twitter.com/search/realtime?q='
# begin loop
def main():
oldTwit = []
newTwit = []
while 1 < 2:
try:
sourceCode = opener.open ('https://twitter.com/search/realtime?q='+keyWord+'&src=hash').read()
splitSource = re.findall (r' <p class="js-tweet-text tweet-text">(.*?)</p>',sourceCode)
for item in splitSource:
#print item
print ''
print ''
print ' '
aTweet = re.sub(r'<.*?>', '',item)
print aTweet
newTwit.append(aTweet)
comparison = difflib.SequenceMatcher(None, newTwit, oldTwit)
howSim = comparison.ratio()
print '##############'
print howSim
oldTwit = [None]
for eachItem in newTwit:
oldTwit.append(eachItem)
newTwit = [None]
time.sleep(howSim*10)
except Exception, e:
print str(e)
print 'errored in the main try'
time.sleep(555)
main()
這爲我提供了我想要收集(我真的不希望分析這些數據的鳴叫,我多用自動收集數據使用試驗蟒蛇連接到我的分貝)
我也有使用MySQLdb的我的數據庫連接,並且是能夠使用簡單的INSERT語句將內容添加到我的數據庫。
import MySQLdb
db=MySQLdb.connect(host="127.0.0.1",user="root",passwd="",db="twitinfo")
cursor = db.cursor()
sql = "INSERT INTO tweets(text) VALUES ('?')"
cursor.execute(sql)
db.commit()
所以我的問題是我怎麼能'用我的插入語句替換'打印,以及我該怎麼做需要添加以使我的價值成爲推文文本?我搜索了高和低,我沒有找到任何有用的東西。我也嘗試過自己,但作爲一個Python新手,試圖猜測它的語法就像在大海撈針中找到針。
SQL使用問號作爲佔位符。您需要找到[MySQLdb](http://mysql-python.sourceforge.net/MySQLdb.html)模塊的文檔,以查看我所猜測的是如何使用值執行SQL是否正確;看起來我已經足夠接近了。有一個古怪的功能;這些例子至少使用'%s'而不是'?'來表示值的放置位置。 –
哦,我明白了,謝謝,這很有幫助。我可以使用我用來打印的相同變量嗎?我將其添加到所述插入件的命令: 主() SQL = 「INSERT INTO解析(文本)VALUES(aTweet)」 cursor.execute(SQL) db.commit() cursor.execute(SQL) db.commit() 我認爲我在正確的軌道上,我沒有得到語法錯誤,並且腳本仍然在編輯後拉入推文,但我的表仍然返回0行。 http://screencast.com/t/vwCFOZWL – user2770466
查看最新的答案。 –