4

我在这里阅读了其他一些答案,但我缺少一些基本的东西。我正在尝试使用 CrawlSpider 从网站中提取图像。

设置.py

BOT_NAME = 'healthycomm'

SPIDER_MODULES = ['healthycomm.spiders']
NEWSPIDER_MODULE = 'healthycomm.spiders'

ITEM_PIPELINES = {'scrapy.contrib.pipeline.images.ImagesPipeline': 1}
IMAGES_STORE = '~/Desktop/scrapy_nsml/healthycomm/images'

项目.py

class HealthycommItem(scrapy.Item):
    page_heading = scrapy.Field()
    page_title = scrapy.Field()
    page_link = scrapy.Field()
    page_content = scrapy.Field()
    page_content_block = scrapy.Field()

    image_url = scrapy.Field()
    image = scrapy.Field()

健康通讯蜘蛛.py

class HealthycommSpiderSpider(CrawlSpider):
    name = "healthycomm_spider"
    allowed_domains = ["healthycommunity.org.au"]
    start_urls = (
        'http://www.healthycommunity.org.au/',
    )
    rules = (Rule(SgmlLinkExtractor(allow=()), callback="parse_items", follow=False), ) 


    def parse_items(self, response):
        content = Selector(response=response).xpath('//body')
        for nodes in content:

            img_urls = nodes.xpath('//img/@src').extract()

            item = HealthycommItem()
            item['page_heading'] = nodes.xpath("//title").extract()
            item["page_title"] = nodes.xpath("//h1/text()").extract()
            item["page_link"] = response.url
            item["page_content"] = nodes.xpath('//div[@class="CategoryDescription"]').extract()
            item['image_url'] = img_urls 
            item['image'] = ['http://www.healthycommunity.org.au' + img for img in img_urls]

            yield item

一般来说,我对 Python 不是很熟悉,但我觉得我在这里遗漏了一些非常基本的东西。

谢谢,杰米

4

1 回答 1

3

如果要使用标准ImagesPipeline,则需要将parse_items方法更改为:

import urlparse
...

    def parse_items(self, response):
        content = Selector(response=response).xpath('//body')
        for nodes in content:

            # build absolute URLs
            img_urls = [urlparse.urljoin(response.url, src)
                        for src in nodes.xpath('//img/@src').extract()]

            item = HealthycommItem()
            item['page_heading'] = nodes.xpath("//title").extract()
            item["page_title"] = nodes.xpath("//h1/text()").extract()
            item["page_link"] = response.url
            item["page_content"] = nodes.xpath('//div[@class="CategoryDescription"]').extract()

            # use "image_urls" instead of "image_url"
            item['image_urls'] = img_urls 

            yield item

并且您的项目定义需要“ images”和“ image_urls”字段(复数,而不是单数)

另一种方法是设置IMAGES_URLS_FIELDIMAGES_RESULT_FIELD适合您的项目定义

于 2014-07-02T13:07:09.550 回答