2014-07-02 4 views
4

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

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' 

items.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 в целом, но я чувствую, что я Здесь нет ничего принципиального.

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

+0

Я думаю, что u пропустил '/', добавляя к изображению. я думаю, что это должно быть http://www.healthycommunity.org.au/ –

+0

Относительный путь возвращается, то есть: /path/path2/image.jpg –

+1

http://stackoverflow.com/questions/8773732/downloading -pictures-with-scrapy check this –

ответ

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_FIELD и IMAGES_RESULT_FIELD, чтобы соответствовать вашему пункту def inition

+0

Does 'urlparse.urljoin (response.url, src)' уважать потенциал ['' tag] (https://developer.mozilla.org/en-US/docs/Web/ HTML/Element/base) для документа? –

+1

@SimonShine, я так не думаю, но новый (er) ['response.urljoin (src)'] (https://docs.scrapy.org/en/latest/topics/request-response.html# scrapy.http.Response.urljoin). См. [Реализация] (https://github.com/scrapy/scrapy/blob/master/scrapy/http/response/text.py#L82). –

Смежные вопросы