Python 将Mysql与scrapy连接时出错
我想抓取url中的所有html_代码,并将它们放在db MySQL中 但我有错误。 错误1054:未知列'$ 我试过很多方法,但都不能纠正错误。 这让我花了很多时间。我只是学刮毛。 希望大家能帮我解决这个问题。多谢各位 Spider_find.pyPython 将Mysql与scrapy连接时出错,python,scrapy,Python,Scrapy,我想抓取url中的所有html_代码,并将它们放在db MySQL中 但我有错误。 错误1054:未知列'$ 我试过很多方法,但都不能纠正错误。 这让我花了很多时间。我只是学刮毛。 希望大家能帮我解决这个问题。多谢各位 Spider_find.py from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from find.items import WebsiteLoader, Fin
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from find.items import WebsiteLoader, FindItem
from scrapy.loader import ItemLoader
class FindSpider(BaseSpider):
name = "find"
allowed_domains = ["tratu.soha.vn"]
start_urls = [
"http://tratu.soha.vn/dict/vn_vn/Sang",
]
def parse(self, response):
item = FindItem()
sel = response.xpath('//*')
item['html_code'] = sel.xpath('//*').extract()[0]
#print item['html_code']
print "CODE HEREEEEEEEEEEEEEEEEEEEEEEEEEEEEe"
yield item
管道.py
from datetime import datetime
import hashlib
import scrapy
from scrapy.exceptions import DropItem
from twisted.enterprise import adbapi
import sys
import MySQLdb
class MySQLStorePipeline(object):
host = 'localhost'
user = 'root'
password = 'success'
db = 'find2'
def __init__(self):
self.conn = MySQLdb.connect(self.host, self.user, self.password, self.db)
self.cursor = self.conn.cursor()
def process_item(self, item, spider):
try:
#self.cursor.execute("""INSERT INTO find2.website(html_code) VALUES ({0})""".format((item['html_code'].encode('utf8'))))
self.cursor.execute("""INSERT INTO `find2`.`website`(`html_code`) VALUES (`${0}`)""".format((item['html_code'].encode('utf8'))))
self.conn.commit()
except MySQLdb.Error, e:
print "ERRRRRRRRRRRRRRRRRRRRRRRRRRRRRO"
print "Error %d: %s" %(e.args[0], e.args[1])
return item
要在python中格式化字符串,我通常会这样做:
“{0}{1}”。格式化('one','two')
因此,请尝试从查询中删除$
符号:
self.cursor.execute("""INSERT INTO `find2`.`website`(`html_code`) VALUES (`{0}`)""".format((item['html_code'].encode('utf8'))))
我假定您的错误发生在
self.cursor.execute("""INSERT INTO `find2`.`website`(`html_code`)
VALUES (`${0}`)""".format((item['html_code'].encode('utf8'))))
(如果能立即将这些信息包括在问题中会非常有帮助;)
这是因为str.format()
不使用$
-语法,而是使用%
-语法。在这种简单的情况下,我会尝试
self.cursor.execute("""INSERT INTO `find2`.`website`(`html_code`)
VALUES (`%s`)""" % item['html_code'].encode('utf8'))
但一般来说,您不应该这样编码,而应该始终使用占位符语法并将值作为参数应用。在这种情况下,实际上必须执行,因为您不知道HTML代码是什么样子的。HTML很可能包含一个“
。这将破坏您通过字符串组合构建的SQL的语法:HTML中的第一个“
将有效地关闭SQL中的值,从而引发格式错误的SQL
所以选择占位符语法:
self.cursor.execute("""INSERT INTO `find2`.`website`(`html_code`)
VALUES (%s)""", (item['html_code'].encode('utf8'),))
让我们看看下一个问题是否是表名中的点…当您将代码墙(与问题完全无关)减少到…时,这个问题会变得更有用。我下次会注意。谢谢我试着去掉“$”符号。但这仍然是错误的。错误未更改。表网站:如果不存在,则创建表
find2
网站(html\u code
文本字符集“utf8”COLLATE“utf8”unicode\u ci”not NULL,id
INT(11)not NULL自动增量,主键(id
)引擎=InnoDB自动增量=2默认字符集=拉丁1;建议的代码更改有什么错误(它不能再抱怨$
了…?)没有或没有$this is error“error 1054:Unknown column”我该怎么办?但我有下一个错误。我的URL有越南语。html代码当我得到它时,这些字符没有格式化!!我该怎么办?