Извлечение изображений в Scrapy

Я прочитал несколько других ответов здесь, но мне не хватает чего-то фундаментального. Я пытаюсь извлечь изображения с веб-сайта с помощью CrawlSpider.

settings.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()

HealthycommSpider.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 в целом, но мне кажется, что я упускаю здесь что-то очень простое.

Спасибо, Джейми.


person Jamie S    schedule 02.07.2014    source источник
comment
я думаю, вы пропустили '/' при добавлении к изображению. я думаю, что это должен быть healthycommunity.org.au   -  person sundar nataraj    schedule 02.07.2014
comment
Возвращается относительный путь, например: /path/path2/image.jpg   -  person Jamie S    schedule 02.07.2014
comment
stackoverflow.com/questions/8773732/ проверьте это   -  person sundar nataraj    schedule 02.07.2014
comment
Оказывается, я пропустил букву s в классе элементов — image_urls вместо image_url. как разочаровывает   -  person Jamie S    schedule 02.07.2014
comment
так твоя проблема решилась   -  person sundar nataraj    schedule 02.07.2014


Ответы (1)


Если вы хотите использовать стандартный 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_FIELD и IMAGES_RESULT_FIELD в соответствии с определением вашего элемента.

person paul trmbrth    schedule 02.07.2014
comment
Учитывает ли urlparse.urljoin(response.url, src) потенциальный тег <base> для документа ? - person Simon Shine; 30.11.2017
comment
@SimonShine, я так не думаю, но новый (er) response.urljoin(src) делает. См. реализация. - person paul trmbrth; 30.11.2017