我的刮刀运行良好,它下载图像并在数据库中注册项目,但我也希望将它们的本地路径保存到我的 MySQL 数据库中,我不知道如何继续。
我在文档中读过这个:
下载图像后,另一个字段(图像)将填充结果。
使用下面的代码,路径没有保存,我收到了这个错误:
return self._values[key]
exceptions.KeyError: 'images'
以下是我的代码摘录:
项目.py:
image_urls = Field()
images = Field()
my_spider.py:
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from project.items import ArtistItem
class MySpider(BaseSpider):
name = 'XXX'
allowed_domains = ['XXX']
start_urls = [
"XXX",
"XXX"
]
def parse(self, response):
x = HtmlXPathSelector(response)
artist = ArtistItem()
artist['url'] = response.url
artist['name'] = x.select("//h1/text()").extract()
artist['city'] = x.select("//span[@class='profile_location']/text()").extract()
artist['style'] = x.select("//span[@class='profile_genre']/text()").extract()
image_urls = x.select('/html/body/div[4]/div/div/div[2]/div[2]/div/a/img/@src').extract()
artist['image_urls'] = ["http:" + x for x in image_urls]
return artist
管道.py:
from scrapy.http import Request
from scrapy.contrib.pipeline.images import ImagesPipeline
from scrapy.exceptions import DropItem
import MySQLdb
import MySQLdb.cursors
import sys
class ProjectPipeline(object):
def __init__(self):
db = MySQLdb.connect(host='localhost', user='XXX', passwd='XXX', db='XXX', charset='utf8',
use_unicode=True)
self.c = db.cursor()
self.c.connection.autocommit(True)
def process_item(self, item, spider):
try:
self.c.execute("""INSERT INTO artist (name, city, style, image_url)
VALUES (%s, %s, %s, %s)""",
(item['name'][0],
item['city'][0],
item['style'][0],
item['images'][0]['path'],
))
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit(1)
return item
我在 parse() 函数中缺少什么?
提前致谢。