#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: imcfy<i@imcfy.com>
#         http://imcfy.com
# Created on 2015-10-24 11:45:17

#################################
'''
模拟访问CB
'''
#################################


import sys
import json
import requests as reqs
import urllib2, urllib
from HTMLParser import HTMLParser
from lxml import etree 
import chardet
import os
import re
import time 
import datetime

from sevencow import CowException
from sevencow import Cow



def now(formatstr):
    if formatstr == '':formatstr='%Y-%m-%d %H:%M:%S'
    d1= datetime.datetime.now()
    return d1.strftime(formatstr)

def SaveToFile(filename, content):
    f = open(filename, 'w+')
    try:
        f.write(content)
    except Exception, e:
        print Exception,":", e
    f.close()

def readerFile(filename):
    result = ""
    reader = open(filename, 'r')
    while True:
        line = reader.readline()
        if line:
            result = result+line
        else:
            break
    reader.close()
    return result


class SimulatePost:
    ''' 模拟登陆 '''
    _post_data = {}
    _hds = {}
    _cookies = {}
    _post_url = {}
    tmp_dict = {}
    def dict_img(self,inputContent):
        for j in range(10):
            self.tmp_dict['imgurl'+str(int(j)+1)] =''
        #-----------------top img------------------
        i = 0
        for m in re.finditer(r'data-normal-img=\"http://img.chinabrands.com/.{0,60}\" data-',inputContent):
            self.tmp_dict['imgurl'+str(int(i))] = m.group().replace("data-normal-img=\"","").replace('?9" data-','')
            i = i + 1
            
        #--------------------main img ------------------------------------
        
        tree=etree.HTML(inputContent)
        nodes=tree.xpath(u"id('goods_desc')/div/div[2]/img/@src")
        if i<10:
            for n in nodes:
                self.tmp_dict['imgurl'+str(int(i))] =n
                i = i + 1
    
        return self.tmp_dict
        
    def get_imgurl(self,url):
        rqs = reqs.Session()
        rsps = rqs.get(url)
        inputContent =rsps.content
        num = 0
        for m in re.finditer(r'data-normal-img=\"http://img.chinabrands.com/.{0,60}\" data-',inputContent):
            if num > 0 :
                break 
            imgurl = m.group().replace("data-normal-img=\"","").replace('?9" data-','')
            num = num + 1
            
        return imgurl
        
    def login(self,url, username, password):
        rqs = reqs.Session()
        rsps = rqs.get(url)

        cookies = ''
        for index, cookie in enumerate(rqs.cookies):
            cookies = cookies+cookie.name+"="+cookie.value+";";
        print 'cookies: ',cookies
        # print 'Code: ',cookie.value

        cCode = cookie.value
        # self._post_data.setdefault('checkCode',cCode)
        
        
        self._post_data = {'email':username, 'password':password}
        self._hds = {
                'Host':'www.chinabrands.com',
                'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0',
                'Accept':'text/plain, */*; q=0.01',
                'Accept-Language':'zh-CN,en-US;q=0.7,en;q=0.3',
                'Accept-Encoding':'gzip, deflate',
                'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
                'X-Requested-With':'XMLHttpRequest',
                'Referer':'http://www.chinabrands.com/m-users-a-sign.htm',
                'Content-Length':'43',
                'Cookie':cookies,
                'Connection':'keep-alive',
                'Pragma':'no-cache',
                'Cache-Control':'no-cache',
              }


        #发送post请求
        posturl = 'http://www.chinabrands.com/m-users-a-act_sign.htm'
        postdata = urllib.urlencode(self._post_data)


        rsps = rqs.post(posturl, data = postdata, headers=self._hds)
        print rsps.content 
        dictcookies={}
        for index, cookie in enumerate(rqs.cookies):
            cookies = cookies+cookie.name+"="+cookie.value+";";
            dictcookies[cookie.name]=cookie.value
        # print 'cookies: ',cookies
        return dictcookies
      

if __name__ == '__main__':

    slogin = SimulatePost()
    # cookies = slogin.login('http://www.chinabrands.com/m-users-a-sign.htm','125769692@qq.com','xlq890210')
    
    # rqs = reqs.Session()
    # rsps = rqs.get('http://www.chinabrands.com/product67300.html',cookies = cookies )
    # SaveToFile( 'out_html.txt',rsps.content)
    
    
    out_html=readerFile('out_html.txt')
    # #---------------------top img ----------------------------------
    # for m in re.finditer(r'data-normal-img=\"http://img.chinabrands.com/.{0,60}\" data-',out_html):
    #     print m.group().replace("data-normal-img=\"","").replace('" data-','')
    
    # #--------------------main img ------------------------------------
    
    # tree=etree.HTML(out_html)
    # nodes=tree.xpath(u"id('goods_desc')/div/div[2]/img/@src")
    
    # for n in nodes:
    #     print 'imgusr: ',n
    
    print slogin.dict_img(out_html)

    #------------------color---------------------------------------------
    # tree=etree.HTML(out_html)
    # nodes=tree.xpath(u"id('bodymain2')/div[4]/div[1]/div[2]/p[5]/select/option")

    # for n in nodes:
    #     print 'Color VALUE: ',''.join(n.text.split())
        
    # tree=etree.HTML(out_html)
    # nodes=tree.xpath(u"id('bodymain2')/div[4]/div[1]/div[2]/p[5]/select/option/@value")

    # for n in nodes:
    #     print 'Color URL: ',n
        
    # #------------------size---------------------------------------------
    # tree=etree.HTML(out_html)
    # nodes=tree.xpath(u"id('bodymain2')/div[4]/div[1]/div[2]/p[6]/select/option")
    # nodes1=tree.xpath(u"id('bodymain2')/div[4]/div[1]/div[2]/p[6]/select/@name")
    
    # if nodes1[0] == 'select_same_goods_64' or nodes1[0] == 'select_same_goods_63':
    #     for n in nodes:
    #         print 'Size VALUE: ', ''.join(n.text.split())
    


         
