Subversion Repositories SmartDukaan

Rev

Rev 20343 | Rev 20376 | 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  
134
        for subAttribute in product['subAttributes']:
135
            sub_supc = subAttribute['supc']
136
            sub_value = subAttribute['value']
137
            sub_name = subAttribute['name']
138
            subAttr = __SubAttributes(sub_supc, color, sub_name, sub_value)
139
            subAttributes_list = r_info.subAttributes
140
            subAttributes_list.append(subAttr)
141
    return supcMap
142
 
143
 
144
 
13754 kshitij.so 145
def scrapeBestSellerMobiles():
146
    global bestSellers
15829 kshitij.so 147
    bestSellers = []
13754 kshitij.so 148
    rank = 1
149
    for z in [0,20,40,60,80]:
150
        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 151
        soup = getSoupObject(url)
18202 kshitij.so 152
        for product in soup.findAll('div',{'class':'product-desc-rating title-section-expand'}):
17390 kshitij.so 153
            try:
154
                supcMap = fetchSupcDetails(product.find('a')['href'],rank, 3)
155
            except:
156
                continue
15829 kshitij.so 157
            bestSellers.append(supcMap)
158
            rank = rank + 1
13754 kshitij.so 159
 
160
def scrapeBestSellerTablets():
161
    global bestSellers
162
    bestSellers = []
163
    rank = 1
164
    for z in [0,20,40,60,80]:
165
        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 166
        soup = getSoupObject(url)
18202 kshitij.so 167
        for product in soup.findAll('div',{'class':'product-desc-rating title-section-expand'}):
168
            supcMap = fetchSupcDetails(product.find('a')['href'],rank, 5)
15829 kshitij.so 169
            bestSellers.append(supcMap)
170
            rank = rank + 1
13754 kshitij.so 171
 
172
 
173
def resetRanks(category):
15829 kshitij.so 174
    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 175
 
14379 kshitij.so 176
def commitBestSellers(category):
177
    global exceptionList
15829 kshitij.so 178
    for bestSeller in bestSellers:
179
        for mapVal in bestSeller.itervalues():
180
            for v in mapVal:
181
                col = list(get_mongo_connection().Catalog.MasterData.find({'identifier':v.identifier.strip(),'source_id':3}))
182
                if len(col) ==0 and len(v.subAttributes) == 0:
183
                    exObj = __Exception(v.identifier.strip(), v.baseColor, "", v.page_url ,v.rank, category, v.product_name)
184
                    exceptionList.append(exObj)
185
                    continue
186
                print v.identifier
187
                print v.rank
188
                get_mongo_connection().Catalog.MasterData.update({'identifier':v.identifier,'source_id':3},{'$set' : {'rank':v.rank,'updatedOn':to_java_date(now)}}, multi=True)
189
                for subAttr in v.subAttributes:
190
                    print "Inside subattr"
191
                    print vars(subAttr)
192
                    col = list(get_mongo_connection().Catalog.MasterData.find({'identifier':subAttr.identifier.strip(),'source_id':3}))
193
                    if len(col) ==0:
194
                        exObj = __Exception(subAttr.identifier.strip(), subAttr.color, subAttr.name+" "+subAttr.value, v.page_url ,v.rank, category, v.product_name)
195
                        exceptionList.append(exObj)
196
                    else:
197
                        print v.identifier
198
                        print v.rank
199
                        get_mongo_connection().Catalog.MasterData.update({'identifier':subAttr.identifier,'source_id':3},{'$set' : {'rank':v.rank,'updatedOn':to_java_date(now)}}, multi=True)
200
    print exceptionList
13754 kshitij.so 201
 
14379 kshitij.so 202
def sendEmail():
203
    message="""<html>
204
            <body>
205
            <h3>Snapdeal Best Sellers not in master</h3>
206
            <table border="1" style="width:100%;">
207
            <thead>
208
            <tr><th>Identifier</th>
209
            <th>Category</th>
210
            <th>Rank</th>
15088 kshitij.so 211
            <th>Product Name</th>
15829 kshitij.so 212
            <th>Color</th>
213
            <th>Description</th>
15088 kshitij.so 214
            <th>Page Url</th>
14379 kshitij.so 215
            </tr></thead>
216
            <tbody>"""
217
    for item in exceptionList:
20343 kshitij.so 218
        encoding =  chardet.detect(item.pageurl)
219
        try:
20344 kshitij.so 220
            message+="""<tr>
221
            <td style="text-align:center">"""+(item.identifier)+"""</td>
222
            <td style="text-align:center">"""+(categoryMap.get(item.category))+"""</td>
223
            <td style="text-align:center">"""+str(item.rank)+"""</td>
224
            <td style="text-align:center">"""+str(item.product_name)+"""</td>
225
            <td style="text-align:center">"""+item.color+"""</td>
226
            <td style="text-align:center">"""+item.desc+"""</td>
227
            <td style="text-align:center">"""+item.pageurl+"""</td>
228
            </tr>"""
20343 kshitij.so 229
        except:
20344 kshitij.so 230
            pass
14379 kshitij.so 231
    message+="""</tbody></table></body></html>"""
232
    print message
233
    #recipients = ['kshitij.sood@saholic.com']
20172 aman.kumar 234
    recipients = ['rajneesh.arora@saholic.com','kshitij.sood@saholic.com','chaitnaya.vats@saholic.com','ritesh.chauhan@saholic.com','khushal.bhatia@saholic.com']
14379 kshitij.so 235
    msg = MIMEMultipart()
236
    msg['Subject'] = "Snapdeal Best Sellers" + ' - ' + str(datetime.now())
237
    msg['From'] = ""
238
    msg['To'] = ",".join(recipients)
239
    msg.preamble = "Snapdeal Best Sellers" + ' - ' + str(datetime.now())
240
    html_msg = MIMEText(message, 'html')
241
    msg.attach(html_msg)
242
 
243
    smtpServer = smtplib.SMTP('localhost')
244
    smtpServer.set_debuglevel(1)
245
    sender = 'dtr@shop2020.in'
246
    try:
247
        smtpServer.sendmail(sender, recipients, msg.as_string())
248
        print "Successfully sent email"
249
    except:
250
        print "Error: unable to send email."
251
 
252
 
253
 
13754 kshitij.so 254
def main():
15829 kshitij.so 255
    import time
13754 kshitij.so 256
    scrapeBestSellerMobiles()
257
    if len(bestSellers) > 0:
15829 kshitij.so 258
        resetRanks(3)
259
        commitBestSellers(3)
13754 kshitij.so 260
    scrapeBestSellerTablets()
261
    if len(bestSellers) > 0:
15829 kshitij.so 262
        resetRanks(5)
263
        commitBestSellers(5)
18202 kshitij.so 264
    print bestSellers
14379 kshitij.so 265
    sendEmail()
13754 kshitij.so 266
 
267
if __name__=='__main__':
268
    main()