Subversion Repositories SmartDukaan

Rev

Rev 20344 | Rev 21135 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
13754 kshitij.so 1
import urllib2
2
import simplejson as json
3
import pymongo
13828 kshitij.so 4
from dtr.utils.utils import to_java_date
5
from datetime import datetime
14257 kshitij.so 6
import optparse
14379 kshitij.so 7
import smtplib
8
from email.mime.text import MIMEText
9
from email.mime.multipart import MIMEMultipart
15829 kshitij.so 10
from BeautifulSoup import BeautifulSoup
11
from dtr.utils.utils import ungzipResponse
12
import json
20343 kshitij.so 13
import chardet
13754 kshitij.so 14
 
14257 kshitij.so 15
con = None
16
parser = optparse.OptionParser()
17
parser.add_option("-m", "--m", dest="mongoHost",
18
                      default="localhost",
19
                      type="string", help="The HOST where the mongo server is running",
20
                      metavar="mongo_host")
21
 
22
(options, args) = parser.parse_args()
23
 
14379 kshitij.so 24
exceptionList = []
15829 kshitij.so 25
noAttributesSupc = []
14379 kshitij.so 26
 
15829 kshitij.so 27
categoryMap = {3:'Mobiles',5:'Tablets'}
28
 
13754 kshitij.so 29
headers = { 
30
           'User-agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11',
31
            'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',      
32
            'Accept-Language' : 'en-US,en;q=0.8',                     
15829 kshitij.so 33
            'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
34
            'Accept-Encoding' : 'gzip,deflate,sdch'
13754 kshitij.so 35
        }
36
 
37
bestSellers = []
13828 kshitij.so 38
now = datetime.now()
15088 kshitij.so 39
BASE_URL = "snapdeal.com/"
13754 kshitij.so 40
 
41
class __RankInfo:
42
 
15829 kshitij.so 43
    def __init__(self, identifier, rank, category, product_name, page_url, baseColor, ppid, subAttributes, live):
13754 kshitij.so 44
        self.identifier = identifier
45
        self.rank  = rank
14379 kshitij.so 46
        self.category  =category
15088 kshitij.so 47
        self.product_name = product_name
48
        self.page_url = page_url 
15829 kshitij.so 49
        self.baseColor = baseColor
50
        self.ppid = ppid
51
        self.subAttributes = subAttributes
52
        self.live = live
53
 
54
class __SubAttributes:
55
 
56
    def __init__(self, identifier, color, name, value):
57
        self.identifier = identifier
58
        self.color = color
59
        self.name = name
60
        self.value = value
13754 kshitij.so 61
 
15829 kshitij.so 62
class __Exception:
63
 
64
    def __init__(self, identifier, color, desc, pageurl, rank, category, product_name):
65
        self.identifier = identifier
66
        self.color = color
67
        self.desc = desc
68
        self.pageurl = pageurl
69
        self.rank = rank
70
        self.category = category
71
        self.product_name = product_name
72
 
73
 
74
 
14257 kshitij.so 75
def get_mongo_connection(host=options.mongoHost, port=27017):
13754 kshitij.so 76
    global con
77
    if con is None:
78
        print "Establishing connection %s host and port %d" %(host,port)
79
        try:
80
            con = pymongo.MongoClient(host, port)
81
        except Exception, e:
82
            print e
83
            return None
84
    return con
85
 
15829 kshitij.so 86
def getSoupObject(url):
87
    print "Getting soup object for"
88
    print url
89
    global RETRY_COUNT
90
    RETRY_COUNT = 1 
91
    while RETRY_COUNT < 10:
92
        try:
93
            soup = None
94
            request = urllib2.Request(url,headers=headers)
95
            response = urllib2.urlopen(request)
96
            response_data = ungzipResponse(response)   
97
            response.close()
98
            try:
99
                page=response_data.decode("utf-8")
100
                soup = BeautifulSoup(page,convertEntities=BeautifulSoup.HTML_ENTITIES)
101
            except:
102
                soup = BeautifulSoup(response_data,convertEntities=BeautifulSoup.HTML_ENTITIES)
103
            if soup is None:
104
                raise
105
            return soup
106
        except Exception as e:
107
            print e
108
            print "Retrying"
109
            RETRY_COUNT = RETRY_COUNT + 1
110
 
111
def fetchSupcDetails(p_url, rank, category):
112
    supcMap = {}
113
    soup = getSoupObject(p_url)
114
    attributes =  soup.find('div',{'id':'attributesJson'}).string
115
    try:
116
        ppid = soup.find('input',{'id':'pppid'})['value']
117
    except:
118
        ppid = p_url[p_url.rfind('/')+1:]
119
    productName = soup.find('input',{'id':'productNamePDP'})['value']
120
    supcMap[ppid] = []
121
    if attributes == "[]":
122
        supc = soup.find('div',{'id':'defaultSupc'}).string
123
        r_info = __RankInfo(supc, rank, category, productName, p_url, "", ppid, [], True)
124
        supcMap[ppid] = [r_info]
125
    p_info = json.loads(attributes)
126
    for product in p_info:
127
        color = product['value']
128
        supc = product['supc']
129
        live = product['live']
130
        r_info = __RankInfo(supc, rank, category, productName, p_url, color, ppid, [], live)
131
        temp = supcMap.get(ppid)
132
        temp.append(r_info)
133
        supcMap[ppid] = temp  
20376 kshitij.so 134
        if product['subAttributes'] is not None:
135
            for subAttribute in product['subAttributes']:
136
                sub_supc = subAttribute['supc']
137
                sub_value = subAttribute['value']
138
                sub_name = subAttribute['name']
139
                subAttr = __SubAttributes(sub_supc, color, sub_name, sub_value)
140
                subAttributes_list = r_info.subAttributes
141
                subAttributes_list.append(subAttr)
15829 kshitij.so 142
    return supcMap
143
 
144
 
145
 
13754 kshitij.so 146
def scrapeBestSellerMobiles():
147
    global bestSellers
15829 kshitij.so 148
    bestSellers = []
13754 kshitij.so 149
    rank = 1
150
    for z in [0,20,40,60,80]:
151
        url = "http://www.snapdeal.com/acors/json/product/get/search/175/%d/20?q=&sort=bstslr&keyword=&clickSrc=&viewType=List&lang=en&snr=false" %(z)
15829 kshitij.so 152
        soup = getSoupObject(url)
20376 kshitij.so 153
        for product in soup.findAll('a',{'class':'dp-widget-link'}):
154
            print product['href']
17390 kshitij.so 155
            try:
20376 kshitij.so 156
                supcMap = fetchSupcDetails(product['href'],rank, 3)
17390 kshitij.so 157
            except:
158
                continue
20376 kshitij.so 159
            print "supcMap ",supcMap
15829 kshitij.so 160
            bestSellers.append(supcMap)
161
            rank = rank + 1
13754 kshitij.so 162
 
163
def scrapeBestSellerTablets():
164
    global bestSellers
165
    bestSellers = []
166
    rank = 1
167
    for z in [0,20,40,60,80]:
168
        url = "http://www.snapdeal.com/acors/json/product/get/search/133/%d/20?sort=bstslr&keyword=&clickSrc=&viewType=List&lang=en&snr=false" %(z)
15829 kshitij.so 169
        soup = getSoupObject(url)
20376 kshitij.so 170
        for product in soup.findAll('a',{'class':'dp-widget-link'}):
171
            print product['href']
172
            try:
173
                supcMap = fetchSupcDetails(product['href'],rank, 5)
174
            except:
175
                continue
176
            print "supcMap ",supcMap
15829 kshitij.so 177
            bestSellers.append(supcMap)
178
            rank = rank + 1
13754 kshitij.so 179
 
180
 
181
def resetRanks(category):
15829 kshitij.so 182
    get_mongo_connection().Catalog.MasterData.update({'rank':{'$gt':0},'source_id':3,'category_id':category},{'$set' : {'rank':0,'updatedOn':to_java_date(now)}}, multi=True)
13754 kshitij.so 183
 
14379 kshitij.so 184
def commitBestSellers(category):
185
    global exceptionList
15829 kshitij.so 186
    for bestSeller in bestSellers:
187
        for mapVal in bestSeller.itervalues():
188
            for v in mapVal:
189
                col = list(get_mongo_connection().Catalog.MasterData.find({'identifier':v.identifier.strip(),'source_id':3}))
190
                if len(col) ==0 and len(v.subAttributes) == 0:
191
                    exObj = __Exception(v.identifier.strip(), v.baseColor, "", v.page_url ,v.rank, category, v.product_name)
192
                    exceptionList.append(exObj)
193
                    continue
194
                print v.identifier
195
                print v.rank
196
                get_mongo_connection().Catalog.MasterData.update({'identifier':v.identifier,'source_id':3},{'$set' : {'rank':v.rank,'updatedOn':to_java_date(now)}}, multi=True)
197
                for subAttr in v.subAttributes:
198
                    print "Inside subattr"
199
                    print vars(subAttr)
200
                    col = list(get_mongo_connection().Catalog.MasterData.find({'identifier':subAttr.identifier.strip(),'source_id':3}))
201
                    if len(col) ==0:
202
                        exObj = __Exception(subAttr.identifier.strip(), subAttr.color, subAttr.name+" "+subAttr.value, v.page_url ,v.rank, category, v.product_name)
203
                        exceptionList.append(exObj)
204
                    else:
205
                        print v.identifier
206
                        print v.rank
207
                        get_mongo_connection().Catalog.MasterData.update({'identifier':subAttr.identifier,'source_id':3},{'$set' : {'rank':v.rank,'updatedOn':to_java_date(now)}}, multi=True)
208
    print exceptionList
13754 kshitij.so 209
 
14379 kshitij.so 210
def sendEmail():
211
    message="""<html>
212
            <body>
213
            <h3>Snapdeal Best Sellers not in master</h3>
214
            <table border="1" style="width:100%;">
215
            <thead>
216
            <tr><th>Identifier</th>
217
            <th>Category</th>
218
            <th>Rank</th>
15088 kshitij.so 219
            <th>Product Name</th>
15829 kshitij.so 220
            <th>Color</th>
221
            <th>Description</th>
15088 kshitij.so 222
            <th>Page Url</th>
14379 kshitij.so 223
            </tr></thead>
224
            <tbody>"""
225
    for item in exceptionList:
20343 kshitij.so 226
        encoding =  chardet.detect(item.pageurl)
227
        try:
20344 kshitij.so 228
            message+="""<tr>
229
            <td style="text-align:center">"""+(item.identifier)+"""</td>
230
            <td style="text-align:center">"""+(categoryMap.get(item.category))+"""</td>
231
            <td style="text-align:center">"""+str(item.rank)+"""</td>
232
            <td style="text-align:center">"""+str(item.product_name)+"""</td>
233
            <td style="text-align:center">"""+item.color+"""</td>
234
            <td style="text-align:center">"""+item.desc+"""</td>
235
            <td style="text-align:center">"""+item.pageurl+"""</td>
236
            </tr>"""
20343 kshitij.so 237
        except:
20344 kshitij.so 238
            pass
14379 kshitij.so 239
    message+="""</tbody></table></body></html>"""
240
    print message
241
    #recipients = ['kshitij.sood@saholic.com']
20172 aman.kumar 242
    recipients = ['rajneesh.arora@saholic.com','kshitij.sood@saholic.com','chaitnaya.vats@saholic.com','ritesh.chauhan@saholic.com','khushal.bhatia@saholic.com']
14379 kshitij.so 243
    msg = MIMEMultipart()
244
    msg['Subject'] = "Snapdeal Best Sellers" + ' - ' + str(datetime.now())
245
    msg['From'] = ""
246
    msg['To'] = ",".join(recipients)
247
    msg.preamble = "Snapdeal Best Sellers" + ' - ' + str(datetime.now())
248
    html_msg = MIMEText(message, 'html')
249
    msg.attach(html_msg)
250
 
251
    smtpServer = smtplib.SMTP('localhost')
252
    smtpServer.set_debuglevel(1)
253
    sender = 'dtr@shop2020.in'
254
    try:
255
        smtpServer.sendmail(sender, recipients, msg.as_string())
256
        print "Successfully sent email"
257
    except:
258
        print "Error: unable to send email."
259
 
260
 
261
 
13754 kshitij.so 262
def main():
15829 kshitij.so 263
    import time
13754 kshitij.so 264
    scrapeBestSellerMobiles()
265
    if len(bestSellers) > 0:
15829 kshitij.so 266
        resetRanks(3)
267
        commitBestSellers(3)
13754 kshitij.so 268
    scrapeBestSellerTablets()
269
    if len(bestSellers) > 0:
15829 kshitij.so 270
        resetRanks(5)
271
        commitBestSellers(5)
18202 kshitij.so 272
    print bestSellers
14379 kshitij.so 273
    sendEmail()
13754 kshitij.so 274
 
275
if __name__=='__main__':
276
    main()