Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
17013 manish.sha 1
import urllib2
2
from BeautifulSoup import BeautifulSoup
3
import pymongo
4
import re
5
from dtr.utils.utils import to_java_date
6
import optparse
7
from datetime import datetime
8
import smtplib
9
from email.mime.text import MIMEText
10
from email.mime.multipart import MIMEMultipart
11
from dtr.utils.utils import fetchResponseUsingProxy, get_mongo_connection, ungzipResponse
12
from pyquery import PyQuery
13
import json
14
import mechanize
15
import urllib
16
 
17
 
18
con = None
19
parser = optparse.OptionParser()
20
parser.add_option("-m", "--m", dest="mongoHost",
21
                      default="localhost",
22
                      type="string", help="The HOST where the mongo server is running",
23
                      metavar="mongo_host")
24
 
25
(options, args) = parser.parse_args()
26
 
27
headers = {
28
            'User-Agent':'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36',
29
            'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',      
30
            'Accept-Language' : 'en-US,en;q=0.8',                     
31
            'Accept-Encoding' : 'gzip,deflate,sdch',
32
            'Host' : 'www.homeshop18.com',
33
            'Referer': 'http://www.homeshop18.com/mobile-phones/categoryid:14569/search:/sort:Popularity/inStock:%28%22true%22%29/start:0/'     
34
}
35
 
36
 
37
exceptionList = []
38
bestSellers = []
39
now = datetime.now()
40
csrfValue = None
41
 
42
class __RankInfo:
43
 
44
    def __init__(self, identifier, rank, category, available_price, in_stock, thumbnail, source_product_name, marketPlaceUrl):
45
        self.identifier = identifier
46
        self.rank  = rank
47
        self.available_price = available_price
48
        self.in_stock = in_stock
49
        self.category = category
50
        self.thumbnail = thumbnail
51
        self.source_product_name = source_product_name
52
        self.marketPlaceUrl = marketPlaceUrl    
53
 
54
def getBrowserObject():
55
    import cookielib
56
    br = mechanize.Browser(factory=mechanize.RobustFactory())
57
    cj = cookielib.LWPCookieJar()
58
    br.set_cookiejar(cj)
59
    br.set_handle_equiv(True)
60
    br.set_handle_redirect(True)
61
    br.set_handle_referer(True)
62
    br.set_handle_robots(False)
63
    br.set_debug_http(False)
64
    br.set_debug_redirects(False)
65
    br.set_debug_responses(False)
66
 
67
    br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
68
 
69
    br.addheaders = [('User-agent','Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11'),
70
                     ('Accept', 'text/html,application/xhtml+xml,application/json,application/xml;q=0.9,*/*;q=0.8'),
71
                     ('Accept-Encoding', 'gzip,deflate,sdch'),                  
72
                     ('Accept-Language', 'en-US,en;q=0.8'),                     
73
                     ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'),
74
                     ('Host' , 'm.homeshop18.com'),
75
                     ('Referer', 'http://m.homeshop18.com/search.mobi?keyword=&categoryId=3027&sortConfig=BEST_SELLER')
76
                     ]
77
    return br
78
 
79
def ungzipResponseBr(r,b):
80
    headers = r.info()
81
    if headers['Content-Encoding']=='gzip':
82
        import gzip
83
        print "********************"
84
        print "Deflating gzip response"
85
        print "********************"
86
        gz = gzip.GzipFile(fileobj=r, mode='rb')
87
        html = gz.read()
88
        gz.close()
89
        headers["Content-type"] = "text/html; charset=utf-8"
90
        r.set_data( html )
91
        b.set_response(r)
92
 
93
def getCsrfValue():
94
    global csrfValue
95
    csrfValUrl = 'http://m.homeshop18.com/search.mobi?keyword=&categoryId=14569&sortConfig=BEST_SELLER'
96
    data = fetchResponseUsingProxy(csrfValUrl, proxy=False )
97
    pq = PyQuery(data)
98
    csrf = pq("input[name=csrf]")
99
    csrfValue = csrf[0].value
100
    print csrfValue
101
 
102
def commitBestSellers(category):
103
    global exceptionList
104
    print "Rank",
105
    print '\t',
106
    print 'Identifier'
107
    for x in bestSellers:
108
        print x.rank,
109
        print '\t',
110
        print x.identifier,
111
        print '\t',
112
        col = list(get_mongo_connection().Catalog.MasterData.find({'identifier':x.identifier, 'source_id':7}))
113
        print "count sku",len(col)
114
        print '\n'
115
        if len(col) == 0:
116
            x.category = category
117
            exceptionList.append(x)
118
        else:
119
            get_mongo_connection().Catalog.MasterData.update({'identifier':x.identifier, 'source_id':7 }, {'$set' : {'rank':x.rank,'updatedOn':to_java_date(now)}})
120
 
121
 
122
def scrapeBestSellerMobiles():
123
    global bestSellers
124
    rank = 0
17040 manish.sha 125
    bestSellers = []
17013 manish.sha 126
    print "Homeshop18 Best Sellers Mobiles..."
127
    for i in range(0,5):
128
        mobileCategoryUrl = 'http://www.homeshop18.com/mobile-phones/categoryid:14569/search:/sort:Popularity/inStock:%28%22true%22%29/start:'+str(i*24)+'/?lazy=true'
129
        #mobileCategoryUrl = "http://m.homeshop18.com/search.mobi?categoryId=14569&isAjax=true&page="+str(i)+"&csrf="+csrfValue
130
        data = fetchResponseUsingProxy(mobileCategoryUrl, proxy=False )
131
        soup = BeautifulSoup(data)
132
        tags = soup.findAll("div", {'class':'inside'})
133
        for tag in tags:
134
            if not tag.has_key('id'):
135
                continue
136
            rank = rank +1
137
            if rank >100:
138
                break
139
            titleTag = tag.find('p', {'class' : 'product_title'})
140
            source_product_name = titleTag.text
141
            productUrl = titleTag.find('a').get('href')
142
            productUrl = 'http://www.homeshop18.com'+str(productUrl)
143
            inStock = 1
144
            identfier = tag['id'].split('_')[1]
145
            available_price = long(tag.find('p',{'class':'price clearfix'}).find('b').text.split(' ')[1])
146
            thumbnail = tag.find('p',{'class':'product_image'}).find('img').get('data-original')
147
            print productUrl, source_product_name, thumbnail, rank, available_price, identfier, inStock
17039 manish.sha 148
            r_info = __RankInfo(identfier, rank, None, available_price, inStock, thumbnail, source_product_name, productUrl)
17013 manish.sha 149
            bestSellers.append(r_info)   
150
 
151
def scrapeBestSellerTablets():
152
    global bestSellers
153
    rank = 0
17040 manish.sha 154
    bestSellers = []
17013 manish.sha 155
    print "Homeshop18 Best Sellers Tablets..."
156
    for i in range(0,5):
157
        tabletCategoryUrl = 'http://www.homeshop18.com/tablets/categoryid:8937/search:Tablets/sort:Popularity/inStock:%28%22true%22%29/start:'+str(i*24)+'/?lazy=true'
158
        data = fetchResponseUsingProxy(tabletCategoryUrl)
159
        soup = BeautifulSoup(data)
160
        tags = soup.findAll("div", {'class':'inside'})
161
        for tag in tags:
162
            if not tag.has_key('id'):
163
                continue
164
            rank = rank +1
165
            if rank >100:
166
                break
167
            titleTag = tag.find('p', {'class' : 'product_title'})
168
            source_product_name = titleTag.text
169
            productUrl = titleTag.find('a').get('href')
170
            productUrl = 'http://www.homeshop18.com'+str(productUrl)
171
            inStock = 1
172
            identfier = tag['id'].split('_')[1]
173
            available_price = long(tag.find('p',{'class':'price clearfix'}).find('b').text.split(' ')[1])
174
            thumbnail = tag.find('p',{'class':'product_image'}).find('img').get('data-original')
175
            print productUrl, source_product_name, thumbnail, rank, available_price, identfier, inStock
17039 manish.sha 176
            r_info = __RankInfo(identfier, rank, None , available_price, inStock, thumbnail, source_product_name, productUrl)
17013 manish.sha 177
            bestSellers.append(r_info)
178
 
179
def resetRanks(category_id):
17037 manish.sha 180
    get_mongo_connection().Catalog.MasterData.update({'rank':{'$gt':0},'source_id':7,'category_id':category_id}, {'$set':{'rank':0}}, upsert=False, multi=True)
17013 manish.sha 181
 
182
def sendEmail():
183
    message="""<html>
184
            <body>
185
            <h3>HomeShop18 Best Sellers not in master</h3>
186
            <table border="1" style="width:100%;">
187
            <thead>
188
            <tr><th>Identifier</th>
189
            <th>Category</th>
190
            <th>Rank</th>
191
            <th>Available_price</th>
192
            <th>In_stock</th>
193
            <th>Thumbnail</th>
194
            <th>Source_product_name</th>
195
            <th>MarketPlaceUrl</th>
196
            </tr></thead>
197
            <tbody>"""
198
    for item in exceptionList:
199
        try:
200
            message+="""<tr>
17039 manish.sha 201
            <td style="text-align:center">"""+str(item.identifier)+"""</td>
17038 manish.sha 202
            <td style="text-align:center">"""+str(item.category)+"""</td>
17013 manish.sha 203
            <td style="text-align:center">"""+str(item.rank)+"""</td>
204
            <td style="text-align:center">"""+str(item.available_price)+"""</td>
205
            <td style="text-align:center">"""+str(item.in_stock)+"""</td>
206
            <td style="text-align:center">"""+str(item.thumbnail)+"""</td>
207
            <td style="text-align:center">"""+str(item.source_product_name)+"""</td>
208
            <td style="text-align:center">"""+str(item.marketPlaceUrl)+"""</td>
209
            </tr>"""
210
        except:
211
            continue
212
    message+="""</tbody></table></body></html>"""
213
    print message
214
    #recipients = ['amit.gupta@saholic.com']
215
    recipients = ['rajneesh.arora@saholic.com','kshitij.sood@saholic.com','chaitnaya.vats@saholic.com','manoj.kumar@saholic.com','amit.gupta@saholic.com']
216
    msg = MIMEMultipart()
217
    msg['Subject'] = "HomeShop18 Best Sellers" + ' - ' + str(datetime.now())
218
    msg['From'] = ""
219
    msg['To'] = ",".join(recipients)
220
    msg.preamble = "HomeShop18 Best Sellers" + ' - ' + str(datetime.now())
221
    html_msg = MIMEText(message, 'html')
222
    msg.attach(html_msg)
223
 
224
    smtpServer = smtplib.SMTP('localhost')
225
    smtpServer.set_debuglevel(1)
226
    sender = 'dtr@shop2020.in'
227
    try:
228
        smtpServer.sendmail(sender, recipients, msg.as_string())
229
        print "Successfully sent email"
230
    except:
231
        print "Error: unable to send email."
232
 
233
def main():
234
    #getCsrfValue()
235
    scrapeBestSellerMobiles()
236
    if len(bestSellers) > 0:
237
        resetRanks(3)
238
        commitBestSellers("MOBILE")
239
    scrapeBestSellerTablets()
240
    if len(bestSellers) > 0:
241
        resetRanks(5)
242
        commitBestSellers("TABLET")
243
    sendEmail()
244
 
245
 
246
if __name__=='__main__':
247
    main()
248
 
249
 
250
 
251