Subversion Repositories SmartDukaan

Rev

Rev 17037 | Rev 17039 | 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
125
    print "Homeshop18 Best Sellers Mobiles..."
126
    for i in range(0,5):
127
        mobileCategoryUrl = 'http://www.homeshop18.com/mobile-phones/categoryid:14569/search:/sort:Popularity/inStock:%28%22true%22%29/start:'+str(i*24)+'/?lazy=true'
128
        #mobileCategoryUrl = "http://m.homeshop18.com/search.mobi?categoryId=14569&isAjax=true&page="+str(i)+"&csrf="+csrfValue
129
        data = fetchResponseUsingProxy(mobileCategoryUrl, proxy=False )
130
        soup = BeautifulSoup(data)
131
        tags = soup.findAll("div", {'class':'inside'})
132
        for tag in tags:
133
            if not tag.has_key('id'):
134
                continue
135
            rank = rank +1
136
            if rank >100:
137
                break
138
            titleTag = tag.find('p', {'class' : 'product_title'})
139
            source_product_name = titleTag.text
140
            productUrl = titleTag.find('a').get('href')
141
            productUrl = 'http://www.homeshop18.com'+str(productUrl)
142
            inStock = 1
143
            identfier = tag['id'].split('_')[1]
144
            available_price = long(tag.find('p',{'class':'price clearfix'}).find('b').text.split(' ')[1])
145
            thumbnail = tag.find('p',{'class':'product_image'}).find('img').get('data-original')
146
            print productUrl, source_product_name, thumbnail, rank, available_price, identfier, inStock
17038 manish.sha 147
            r_info = __RankInfo(identfier, rank, "Mobile" , available_price, inStock, thumbnail, source_product_name, productUrl)
17013 manish.sha 148
            bestSellers.append(r_info)   
149
 
150
def scrapeBestSellerTablets():
151
    global bestSellers
152
    rank = 0
153
    print "Homeshop18 Best Sellers Tablets..."
154
    for i in range(0,5):
155
        tabletCategoryUrl = 'http://www.homeshop18.com/tablets/categoryid:8937/search:Tablets/sort:Popularity/inStock:%28%22true%22%29/start:'+str(i*24)+'/?lazy=true'
156
        data = fetchResponseUsingProxy(tabletCategoryUrl)
157
        soup = BeautifulSoup(data)
158
        tags = soup.findAll("div", {'class':'inside'})
159
        for tag in tags:
160
            if not tag.has_key('id'):
161
                continue
162
            rank = rank +1
163
            if rank >100:
164
                break
165
            titleTag = tag.find('p', {'class' : 'product_title'})
166
            source_product_name = titleTag.text
167
            productUrl = titleTag.find('a').get('href')
168
            productUrl = 'http://www.homeshop18.com'+str(productUrl)
169
            inStock = 1
170
            identfier = tag['id'].split('_')[1]
171
            available_price = long(tag.find('p',{'class':'price clearfix'}).find('b').text.split(' ')[1])
172
            thumbnail = tag.find('p',{'class':'product_image'}).find('img').get('data-original')
173
            print productUrl, source_product_name, thumbnail, rank, available_price, identfier, inStock
17038 manish.sha 174
            r_info = __RankInfo(identfier, rank, "Tablets" , available_price, inStock, thumbnail, source_product_name, productUrl)
17013 manish.sha 175
            bestSellers.append(r_info)
176
 
177
def resetRanks(category_id):
17037 manish.sha 178
    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 179
 
180
def sendEmail():
181
    message="""<html>
182
            <body>
183
            <h3>HomeShop18 Best Sellers not in master</h3>
184
            <table border="1" style="width:100%;">
185
            <thead>
186
            <tr><th>Identifier</th>
187
            <th>Category</th>
188
            <th>Rank</th>
189
            <th>Available_price</th>
190
            <th>In_stock</th>
191
            <th>Thumbnail</th>
192
            <th>Source_product_name</th>
193
            <th>MarketPlaceUrl</th>
194
            </tr></thead>
195
            <tbody>"""
196
    for item in exceptionList:
197
        try:
198
            message+="""<tr>
199
            <td style="text-align:center">"""+(item.identifier)+"""</td>
17038 manish.sha 200
            <td style="text-align:center">"""+str(item.category)+"""</td>
17013 manish.sha 201
            <td style="text-align:center">"""+str(item.rank)+"""</td>
202
            <td style="text-align:center">"""+str(item.available_price)+"""</td>
203
            <td style="text-align:center">"""+str(item.in_stock)+"""</td>
204
            <td style="text-align:center">"""+str(item.thumbnail)+"""</td>
205
            <td style="text-align:center">"""+str(item.source_product_name)+"""</td>
206
            <td style="text-align:center">"""+str(item.marketPlaceUrl)+"""</td>
207
            </tr>"""
208
        except:
209
            continue
210
    message+="""</tbody></table></body></html>"""
211
    print message
212
    #recipients = ['amit.gupta@saholic.com']
213
    recipients = ['rajneesh.arora@saholic.com','kshitij.sood@saholic.com','chaitnaya.vats@saholic.com','manoj.kumar@saholic.com','amit.gupta@saholic.com']
214
    msg = MIMEMultipart()
215
    msg['Subject'] = "HomeShop18 Best Sellers" + ' - ' + str(datetime.now())
216
    msg['From'] = ""
217
    msg['To'] = ",".join(recipients)
218
    msg.preamble = "HomeShop18 Best Sellers" + ' - ' + str(datetime.now())
219
    html_msg = MIMEText(message, 'html')
220
    msg.attach(html_msg)
221
 
222
    smtpServer = smtplib.SMTP('localhost')
223
    smtpServer.set_debuglevel(1)
224
    sender = 'dtr@shop2020.in'
225
    try:
226
        smtpServer.sendmail(sender, recipients, msg.as_string())
227
        print "Successfully sent email"
228
    except:
229
        print "Error: unable to send email."
230
 
231
def main():
232
    #getCsrfValue()
233
    scrapeBestSellerMobiles()
234
    if len(bestSellers) > 0:
235
        resetRanks(3)
236
        commitBestSellers("MOBILE")
237
    scrapeBestSellerTablets()
238
    if len(bestSellers) > 0:
239
        resetRanks(5)
240
        commitBestSellers("TABLET")
241
    sendEmail()
242
 
243
 
244
if __name__=='__main__':
245
    main()
246
 
247
 
248
 
249