Subversion Repositories SmartDukaan

Rev

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