Subversion Repositories SmartDukaan

Rev

Rev 17067 | Rev 17069 | 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 re
4
from dtr.utils.utils import to_java_date
5
import optparse
6
from datetime import datetime
7
import smtplib
8
from email.mime.text import MIMEText
9
from email.mime.multipart import MIMEMultipart
10
from dtr.utils.utils import fetchResponseUsingProxy, get_mongo_connection, ungzipResponse
11
import json
12
import urllib
13
 
14
 
15
con = None
16
parser = optparse.OptionParser()
17
parser.add_option("-m", "--m", dest="mongoHost",
18
                      default="localhost",
19
                      type="string", help="The HOST where the mongo server is running",
20
                      metavar="mongo_host")
21
 
22
(options, args) = parser.parse_args()
23
 
24
headers = {
25
            'User-Agent':'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36',
26
            'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',      
27
            'Accept-Language' : 'en-US,en;q=0.8',                     
28
            'Accept-Encoding' : 'gzip,deflate,sdch',
29
            'Host' : 'www.homeshop18.com',
30
            'Referer': 'http://www.homeshop18.com/mobile-phones/categoryid:14569/search:/sort:Popularity/inStock:%28%22true%22%29/start:0/'     
31
}
32
 
33
 
34
exceptionList = []
35
bestSellers = []
36
now = datetime.now()
37
csrfValue = None
38
 
39
class __RankInfo:
40
 
41
    def __init__(self, identifier, rank, category, available_price, in_stock, thumbnail, source_product_name, marketPlaceUrl):
42
        self.identifier = identifier
43
        self.rank  = rank
44
        self.available_price = available_price
45
        self.in_stock = in_stock
46
        self.category = category
47
        self.thumbnail = thumbnail
48
        self.source_product_name = source_product_name
49
        self.marketPlaceUrl = marketPlaceUrl    
50
 
51
def commitBestSellers(category):
52
    global exceptionList
53
    print "Rank",
54
    print '\t',
55
    print 'Identifier'
56
    for x in bestSellers:
57
        print x.rank,
58
        print '\t',
59
        print x.identifier,
60
        print '\t',
17068 kshitij.so 61
        col = list(get_mongo_connection(host=options.mongoHost).Catalog.MasterData.find({'identifier':x.identifier, 'source_id':7}))
17013 manish.sha 62
        print "count sku",len(col)
63
        print '\n'
64
        if len(col) == 0:
65
            x.category = category
66
            exceptionList.append(x)
67
        else:
17068 kshitij.so 68
            get_mongo_connection(host=options.mongoHost).Catalog.MasterData.update({'identifier':x.identifier, 'source_id':7 }, {'$set' : {'rank':x.rank,'updatedOn':to_java_date(now)}})
17013 manish.sha 69
 
70
 
71
def scrapeBestSellerMobiles():
72
    global bestSellers
73
    rank = 0
17040 manish.sha 74
    bestSellers = []
17013 manish.sha 75
    print "Homeshop18 Best Sellers Mobiles..."
76
    for i in range(0,5):
77
        mobileCategoryUrl = 'http://www.homeshop18.com/mobile-phones/categoryid:14569/search:/sort:Popularity/inStock:%28%22true%22%29/start:'+str(i*24)+'/?lazy=true'
78
        #mobileCategoryUrl = "http://m.homeshop18.com/search.mobi?categoryId=14569&isAjax=true&page="+str(i)+"&csrf="+csrfValue
79
        data = fetchResponseUsingProxy(mobileCategoryUrl, proxy=False )
80
        soup = BeautifulSoup(data)
81
        tags = soup.findAll("div", {'class':'inside'})
82
        for tag in tags:
83
            if not tag.has_key('id'):
84
                continue
85
            rank = rank +1
86
            if rank >100:
87
                break
88
            titleTag = tag.find('p', {'class' : 'product_title'})
89
            source_product_name = titleTag.text
90
            productUrl = titleTag.find('a').get('href')
91
            productUrl = 'http://www.homeshop18.com'+str(productUrl)
92
            inStock = 1
93
            identfier = tag['id'].split('_')[1]
94
            available_price = long(tag.find('p',{'class':'price clearfix'}).find('b').text.split(' ')[1])
95
            thumbnail = tag.find('p',{'class':'product_image'}).find('img').get('data-original')
96
            print productUrl, source_product_name, thumbnail, rank, available_price, identfier, inStock
17039 manish.sha 97
            r_info = __RankInfo(identfier, rank, None, available_price, inStock, thumbnail, source_product_name, productUrl)
17013 manish.sha 98
            bestSellers.append(r_info)   
99
 
100
def scrapeBestSellerTablets():
101
    global bestSellers
102
    rank = 0
17040 manish.sha 103
    bestSellers = []
17013 manish.sha 104
    print "Homeshop18 Best Sellers Tablets..."
105
    for i in range(0,5):
106
        tabletCategoryUrl = 'http://www.homeshop18.com/tablets/categoryid:8937/search:Tablets/sort:Popularity/inStock:%28%22true%22%29/start:'+str(i*24)+'/?lazy=true'
107
        data = fetchResponseUsingProxy(tabletCategoryUrl)
108
        soup = BeautifulSoup(data)
109
        tags = soup.findAll("div", {'class':'inside'})
110
        for tag in tags:
111
            if not tag.has_key('id'):
112
                continue
113
            rank = rank +1
114
            if rank >100:
115
                break
116
            titleTag = tag.find('p', {'class' : 'product_title'})
117
            source_product_name = titleTag.text
118
            productUrl = titleTag.find('a').get('href')
119
            productUrl = 'http://www.homeshop18.com'+str(productUrl)
120
            inStock = 1
121
            identfier = tag['id'].split('_')[1]
122
            available_price = long(tag.find('p',{'class':'price clearfix'}).find('b').text.split(' ')[1])
123
            thumbnail = tag.find('p',{'class':'product_image'}).find('img').get('data-original')
124
            print productUrl, source_product_name, thumbnail, rank, available_price, identfier, inStock
17039 manish.sha 125
            r_info = __RankInfo(identfier, rank, None , available_price, inStock, thumbnail, source_product_name, productUrl)
17013 manish.sha 126
            bestSellers.append(r_info)
127
 
128
def resetRanks(category_id):
17068 kshitij.so 129
    get_mongo_connection(host=options.mongoHost).Catalog.MasterData.update({'rank':{'$gt':0},'source_id':7,'category_id':category_id}, {'$set':{'rank':0}}, upsert=False, multi=True)
17013 manish.sha 130
 
131
def sendEmail():
132
    message="""<html>
133
            <body>
134
            <h3>HomeShop18 Best Sellers not in master</h3>
135
            <table border="1" style="width:100%;">
136
            <thead>
137
            <tr><th>Identifier</th>
138
            <th>Category</th>
139
            <th>Rank</th>
140
            <th>Available_price</th>
141
            <th>In_stock</th>
142
            <th>Thumbnail</th>
143
            <th>Source_product_name</th>
144
            <th>MarketPlaceUrl</th>
145
            </tr></thead>
146
            <tbody>"""
147
    for item in exceptionList:
148
        try:
149
            message+="""<tr>
17039 manish.sha 150
            <td style="text-align:center">"""+str(item.identifier)+"""</td>
17038 manish.sha 151
            <td style="text-align:center">"""+str(item.category)+"""</td>
17013 manish.sha 152
            <td style="text-align:center">"""+str(item.rank)+"""</td>
153
            <td style="text-align:center">"""+str(item.available_price)+"""</td>
154
            <td style="text-align:center">"""+str(item.in_stock)+"""</td>
155
            <td style="text-align:center">"""+str(item.thumbnail)+"""</td>
156
            <td style="text-align:center">"""+str(item.source_product_name)+"""</td>
157
            <td style="text-align:center">"""+str(item.marketPlaceUrl)+"""</td>
158
            </tr>"""
159
        except:
160
            continue
161
    message+="""</tbody></table></body></html>"""
162
    print message
163
    #recipients = ['amit.gupta@saholic.com']
164
    recipients = ['rajneesh.arora@saholic.com','kshitij.sood@saholic.com','chaitnaya.vats@saholic.com','manoj.kumar@saholic.com','amit.gupta@saholic.com']
165
    msg = MIMEMultipart()
166
    msg['Subject'] = "HomeShop18 Best Sellers" + ' - ' + str(datetime.now())
167
    msg['From'] = ""
168
    msg['To'] = ",".join(recipients)
169
    msg.preamble = "HomeShop18 Best Sellers" + ' - ' + str(datetime.now())
170
    html_msg = MIMEText(message, 'html')
171
    msg.attach(html_msg)
172
 
173
    smtpServer = smtplib.SMTP('localhost')
174
    smtpServer.set_debuglevel(1)
175
    sender = 'dtr@shop2020.in'
176
    try:
177
        smtpServer.sendmail(sender, recipients, msg.as_string())
178
        print "Successfully sent email"
179
    except:
180
        print "Error: unable to send email."
181
 
182
def main():
183
    #getCsrfValue()
184
    scrapeBestSellerMobiles()
185
    if len(bestSellers) > 0:
186
        resetRanks(3)
187
        commitBestSellers("MOBILE")
188
    scrapeBestSellerTablets()
189
    if len(bestSellers) > 0:
190
        resetRanks(5)
191
        commitBestSellers("TABLET")
192
    sendEmail()
193
 
194
 
195
if __name__=='__main__':
196
    main()
197
 
198
 
199
 
200