3

Scrapy を使用して HTML のみの Web サイトをダウンロードしようとしています。これを実現するために CrawlSpider クラスを使用しています。これが私のパーサーの外観です。私のクローラーはページの HTML ソースをダウンロードし、Web サイトのローカル ミラーを作成します。Web サイトを正常にミラーリングしますが、画像はありません。各ページに添付された画像をダウンロードするために、次を追加してみました。

def parse_link(self, response):
        # Download the source of the page

        # CODE HERE

        # Now search for images

        x = HtmlXPathSelector(response)
        imgs = x.select('//img/@src').extract()

        # Download images

        for i in imgs:
            r = Request(urljoin(response.url, i), callback=self.parse_link)
            # execute the request here

Scrapy's Documentationの例では、パーサーは Request オブジェクトを返し、それが実行されるようです。

応答を取得するために、手動で要求を実行する方法はありますか? parse_link 呼び出しごとに複数のリクエストを実行する必要があります。

4

1 に答える 1

2

画像パイプラインを使用して画像をダウンロードできます。または、リクエストを手動で実行する場合は、次を使用しますyield

def parse_link(self, response):
    """Download the source of the page"""

    # CODE HERE

    item = my_loader.load_item()

    # Now search for images

    imgs = HtmlXPathSelector(response).select('//img/@src').extract()

    # Download images

    path = '/local/path/to/where/i/want/the/images/'
    item['path'] = path

    for i in imgs:
        image_src = i[0]
        item['images'].append(image_src)
        yield Request(urljoin(response.url, image_src),
                callback=self.parse_images,
                meta=dict(path=path))

    yield item

def parse_images(self, response):
    """Save images to disk"""

    path = response.meta.get('path')

    n = get_the_filename(response.url)
    f = open(path + n, 'wb')
    f.write(response.body)
于 2013-03-08T15:37:46.100 に答える