# -*- coding: utf-8 -*-
import scrapy
from scrapy import Request
from tut.items import TutItem


class ExampleSpider(scrapy.Spider):
    name = "example"
    allowed_domains = ["taobaocdn.com","taobao.com"]
    start_urls = [
        "http://detail.tmall.com/item.htm?spm=a230r.1.14.1.vwY1Pf&id=40858242964&ad_id=&am_id=&cm_id=140105335569ed55e27b&pm_id=&abbucket=13",
        #"http://item.taobao.com/item.htm?spm=a217f.1098429.1998023764.138.P5tCp3&id=40596639590&scm=1029.minilist-17.bts2.50016768&ppath=&sku=&ug=#detail",
        #"http://item.taobao.com/item.htm?id=40596639590",
        #"http://item.taobao.com/item.htm?spm=a219r.lm874.14.47.eKPqVi&id=35146160310&ns=1&abbucket=10#detail",
    ]

    def despach(self,respnse):
        murl=response.xpath('//script').re(r'"descUrl":"\s*(.*?)"')
        if len(murl)>0:
            return Request(murl[0], callback=self.parse2)
        murl=response.xpath('//script').re(r'g_config.dynamicScript\("(.*)"\)')
        if len(murl)>0:
            return Request(murl[0], callback=self.parse2)
            
        

    def parse(self, response):
        #murl=response.xpath('//script').re(r'"descUrl":"\s*(.*?)"')[0]
        #print murl
        #return Request(murl, callback=self.parse2)
        murl=response.xpath('//script').re(r'"descUrl":"\s*(.*?)"')
        if len(murl)>0:
            return Request(murl[0], callback=self.parse2)
        murl=response.xpath('//script').re(r'g_config.dynamicScript\("(.*)"\)')
        if len(murl)>0:
            return Request(murl[0], callback=self.parse2)

    def parse2(self,response):
        imgsrc=response.xpath('//img//@src').extract()
        #m=[]
        #for x in imgsrc:
        #    m.append(x)

        t=TutItem()
        t['image_urls']=imgsrc
        return t
