Subversion Repositories SmartDukaan

Rev

Rev 15088 | Rev 17390 | 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']
154
            supcMap = fetchSupcDetails(product.find('a')['href'],rank, 3)
155
            bestSellers.append(supcMap)
156
            rank = rank + 1
13754 kshitij.so 157
 
158
def scrapeBestSellerTablets():
159
    global bestSellers
160
    bestSellers = []
161
    rank = 1
162
    for z in [0,20,40,60,80]:
163
        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 164
        soup = getSoupObject(url)
165
        for product in soup.findAll('div',{'class':'outerImg'}):
166
            print product.find('a')['pogid']
167
            print product.find('a')['href']
168
            supcMap = fetchSupcDetails(product.find('a')['href'],rank, 5)
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:
218
        message+="""<tr>
219
        <td style="text-align:center">"""+(item.identifier)+"""</td>
15829 kshitij.so 220
        <td style="text-align:center">"""+(categoryMap.get(item.category))+"""</td>
14379 kshitij.so 221
        <td style="text-align:center">"""+str(item.rank)+"""</td>
15088 kshitij.so 222
        <td style="text-align:center">"""+str(item.product_name)+"""</td>
15829 kshitij.so 223
        <td style="text-align:center">"""+item.color+"""</td>
224
        <td style="text-align:center">"""+item.desc+"""</td>
225
        <td style="text-align:center">"""+item.pageurl+"""</td>
14379 kshitij.so 226
        </tr>"""
227
    message+="""</tbody></table></body></html>"""
228
    print message
229
    #recipients = ['kshitij.sood@saholic.com']
230
    recipients = ['rajneesh.arora@saholic.com','kshitij.sood@saholic.com','chaitnaya.vats@saholic.com','manoj.kumar@saholic.com']
231
    msg = MIMEMultipart()
232
    msg['Subject'] = "Snapdeal Best Sellers" + ' - ' + str(datetime.now())
233
    msg['From'] = ""
234
    msg['To'] = ",".join(recipients)
235
    msg.preamble = "Snapdeal Best Sellers" + ' - ' + str(datetime.now())
236
    html_msg = MIMEText(message, 'html')
237
    msg.attach(html_msg)
238
 
239
    smtpServer = smtplib.SMTP('localhost')
240
    smtpServer.set_debuglevel(1)
241
    sender = 'dtr@shop2020.in'
242
    try:
243
        smtpServer.sendmail(sender, recipients, msg.as_string())
244
        print "Successfully sent email"
245
    except:
246
        print "Error: unable to send email."
247
 
248
 
249
 
13754 kshitij.so 250
def main():
15829 kshitij.so 251
    import time
13754 kshitij.so 252
    scrapeBestSellerMobiles()
253
    if len(bestSellers) > 0:
15829 kshitij.so 254
        resetRanks(3)
255
        commitBestSellers(3)
13754 kshitij.so 256
    scrapeBestSellerTablets()
257
    if len(bestSellers) > 0:
15829 kshitij.so 258
        resetRanks(5)
259
        commitBestSellers(5)
14379 kshitij.so 260
 
261
    sendEmail()
13754 kshitij.so 262
 
263
if __name__=='__main__':
264
    main()