1

スクレーパーはうまく機能しており、画像をダウンロードしてアイテムをデータベースに登録しますが、それらのローカル パスを 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() 関数に欠けているものは何ですか?
前もって感謝します。

4

2 に答える 2

1

ITEM_PIPELINES 設定でのコンポーネントの優先度は、画像を DB に保存するために重要です。

たとえば、アイテムを格納するために MongoDB を使用している場合です。settings.py でパイプライン コンポーネントの優先順位を設定する方法は次のとおりです。

ITEM_PIPELINES = {
    'scrapy.contrib.pipeline.images.ImagesPipeline':1,
    'yourscrapyproject.pipelines.MongoDBPipeline':100}

上記の設定により、画像情報を格納するためにコントロールが MongoDBPipeline に移動する前に、画像が処理され、item['image'] が入力されることが保証されます。

このドキュメントの最後のセクションで、ITEM_PIPELINES の優先順位の設定について詳しく読むことができます: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

これを理解するのに何時間もかかったので、同じ問題に直面している他の人に役立つようにここにメモしてください.

于 2014-08-04T09:09:44.593 に答える
0

あはは。画像のダウンロードに関するスクレイピー ドキュメントとimages.py のソース ファイルを読みました。

理論的には、あなたがしていることはうまくいくはずですが、保存された画像パスを各アイテムに明示的に追加するカスタム画像パイプラインを作成する方が簡単かもしれません. 便利なことに、与えられた例はまさにそれを行います。:)

それを実装したら、ProjectPipeline の process_item を次のように変更します。

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['image_paths'],
                       ))

    except MySQLdb.Error, e:
        print "Error %d: %s" % (e.args[0], e.args[1])
        sys.exit(1)

    return item

カスタム イメージ パイプライン ファイルを参照するように settings.py ファイルを更新することを忘れないでください。

于 2013-05-03T23:47:23.647 に答える