2015-07-21 145 views
2

我試圖使用Python和BeautifulSoup來抓取一些Web信息,通過它迭代,然後插入一些片段到sqlite3數據庫。但我一直想出這個錯誤:Python和sqlite3拋出一個錯誤:sqlite3.OperationalError:附近的「s」:語法錯誤

文件 「/Users/Chris/Desktop/BS4/TBTfile.py」,線路103,在TBTscrape c.execute(項目) sqlite3.OperationalError:近 「S」 :語法錯誤

對於非常類似的刮板,此相同的代碼工作正常,不會拋出這些錯誤。以下是其中的一部分:

listicle.append("INSERT INTO headlines (heds, url, image_loc, time, source) VALUES ('" + TBTheadline + "', '" + TBTurl + "', '" + imageName + "', '" + TBTpostDate + "', '" + source + "')") 

    else: 
     print "TBT item already in database" 

print listicle 

for item in listicle: 
    c.execute(item) 
    conn.commit() 
    row = c.fetchall() 
    print "This has been inserted succcessfully: ", item 

回答

7

您將所收集的數據連接到您的SQL語句中。 從來沒有這樣做,它是mother of all anti-patterns。除了你正在看到的問題(可能是由於刮掉的HTML中的'或類似的字符),你的代碼中有一個巨大的安全漏洞(在你的情況下可能並不重要)。

無論如何,sqlite3有一個很好的方式做你想要的:executemany。在你的情況下,

listicle.append((TBTheadline,TBTurl,imageName,TBTpostDate,source)) 

conn.executemany("INSERT INTO headlines (heds, url, image_loc, time, source) VALUES (?,?,?,?,?)", listicle) 
+0

哇,這太容易了。我還沒有遇到過。美麗,謝謝! – Chris

相關問題