Python 将html源代码保存到
我正在尝试将网站源代码保存到MySQL数据库中。使用urllib成功检索到源。接下来保存数据。与db的连接很好,问题在于保存源代码,因为当我从insert语句中删除源代码时,一切都很好Python 将html源代码保存到,python,mysql,Python,Mysql,我正在尝试将网站源代码保存到MySQL数据库中。使用urllib成功检索到源。接下来保存数据。与db的连接很好,问题在于保存源代码,因为当我从insert语句中删除源代码时,一切都很好 # get the webpage source f = urllib.urlopen(row_urls['url']) source_fetched = f.read() f.close() # Save the webpage source scrapy_ur
# get the webpage source
f = urllib.urlopen(row_urls['url'])
source_fetched = f.read()
f.close()
# Save the webpage source
scrapy_url_id = row_urls['id']
url = row_urls['url']
created = datetime.datetime.now()
source = unicode(source_fetched,'utf-8')
cur_webpage_save = con.cursor(mdb.cursors.DictCursor)
cur_webpage_save.execute("""INSERT INTO webpage(scrapy_url_id,url,created,source) VALUES('%s', '%s', '%s', '%s');""" %(scrapy_url_id, url, created, source))
我猜它需要对需要转义的字符进行处理,我尝试了这个方法,但它生成了相同的错误:
cur_webpage_save.execute(mdb.escape_string("""INSERT INTO webpage(scrapy_url_id,url,created,source) VALUES('%s', '%s', '%s', '%s');""" %(scrapy_url_id, url, created, source)))
下面您可以看到错误。我做错了什么
Traceback (most recent call last):
File "clean.py", line 55, in <module>
cur_webpage_save.execute(mdb.escape_string("""INSERT INTO webpage(scrapy_url_id,url,created,source) VALUES('%s', '%s', '%s', '%s');""" %(scrapy_url_id, url, created, source)))
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\\'4\\', \\'http://example.com/test.html?id=108185\\', \\'2012-10-28' at line 1")
回溯(最近一次呼叫最后一次):
文件“clean.py”,第55行,在
cur_webpage_save.execute(mdb.escape_string(““”插入网页(创建的url地址id、url、源)值(“%s”、“s”、“s”、“s”);“%”(创建的url地址id、url、源)))
文件“/usr/lib/python2.7/dist packages/MySQLdb/cursors.py”,执行中的第174行
errorhandler(self、exc、value)
文件“/usr/lib/python2.7/dist packages/MySQLdb/connections.py”,第36行,在defaulterrorhandler中
提高errorclass,errorvalue
_mysql\u exceptions.ProgrammingError:(1064,“您的SQL语法有错误;请查看与您的mysql服务器版本对应的手册,以了解在“\\'4\\”和“\\”附近使用的正确语法http://example.com/test.html?id=108185\\“,\\'2012-10-28'第1行”)
不要使用字符串格式将数据放入数据库,而是使用SQL参数:
cur_webpage_save.execute("""INSERT INTO webpage(scrapy_url_id,url,created,source) VALUES(%s, %s, %s, %s);""", (scrapy_url_id, url, created, source))
对于MySQLdb,语法几乎相同,只需删除单引号
数据库适配器会将每个
%s
替换为正确引用的字符串值。这还可以防止SQL注入攻击。感谢@martijn pieters的提示,现在它可以正常工作了!我将确保我也将调整脚本中的其他几个查询。-我得等几分钟才能接受你的回答。顺便说一句,在接近尾声时需要再加上一个)不,我不这么认为;每个(
都有一个平衡)
据我所知。Martjjn你是对的,我猜复制和粘贴出了问题,在执行时,我得到了一个关于丢失的错误)。很抱歉给你带来了困惑。