Python和sqlite3抛出错误:sqlite3.OperationalError:near" s":语法错误

时间:2015-07-21 21:29:37

标签: python sqlite web-scraping

我尝试使用Python和BeautifulSoup来抓取一些网页信息,迭代它然后将一些部分插入到sqlite3数据库中。但我一直想出这个错误:

File" /Users/Chris/Desktop/BS4/TBTfile.py" ;,第103行,在TBTscrape中     c.execute(项目) sqlite3.OperationalError:near" 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

1 个答案:

答案 0 :(得分: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)