スクレーパーはうまく機能しており、画像をダウンロードしてアイテムをデータベースに登録しますが、それらのローカル パスを MySQL データベースに保存したいのですが、どうすればよいかわかりません。
私はドキュメントでこれを読んだ:
画像がダウンロードされると、別のフィールド (画像) に結果が入力されます。
以下のコードでは、パスが保存されず、次のエラーが発生しました。
return self._values[key]
exceptions.KeyError: 'images'
ここに私のコードの抜粋があります:
items.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() 関数に欠けているものは何ですか?
前もって感謝します。