Subversion Repositories SmartDukaan

Rev

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