Subversion Repositories SmartDukaan

Rev

Rev 14379 | Rev 18284 | 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
from BeautifulSoup import BeautifulSoup
3
import pymongo
4
import re
13828 kshitij.so 5
from dtr.utils.utils import to_java_date
6
from datetime import datetime
14257 kshitij.so 7
import optparse
14379 kshitij.so 8
import smtplib
9
from email.mime.text import MIMEText
10
from email.mime.multipart import MIMEMultipart
13754 kshitij.so 11
 
14379 kshitij.so 12
 
13754 kshitij.so 13
con = None
14257 kshitij.so 14
parser = optparse.OptionParser()
15
parser.add_option("-m", "--m", dest="mongoHost",
16
                      default="localhost",
17
                      type="string", help="The HOST where the mongo server is running",
18
                      metavar="mongo_host")
19
 
20
(options, args) = parser.parse_args()
21
 
13754 kshitij.so 22
bestSellers = []
13828 kshitij.so 23
now = datetime.now()
14379 kshitij.so 24
exceptionList = []
13754 kshitij.so 25
 
26
class __RankInfo:
27
 
14379 kshitij.so 28
    def __init__(self, identifier, rank, category):
13754 kshitij.so 29
        self.identifier = identifier
30
        self.rank  = rank
14379 kshitij.so 31
        self.category = category
13754 kshitij.so 32
 
14257 kshitij.so 33
def get_mongo_connection(host=options.mongoHost, port=27017):
13754 kshitij.so 34
    global con
35
    if con is None:
36
        print "Establishing connection %s host and port %d" %(host,port)
37
        try:
38
            con = pymongo.MongoClient(host, port)
39
        except Exception, e:
40
            print e
41
            return None
42
    return con
43
 
44
def getSoupObject(url):
45
    print "Getting soup object for"
46
    print url
47
    global RETRY_COUNT
48
    RETRY_COUNT = 1 
49
    while RETRY_COUNT < 10:
50
        try:
51
            soup = None
52
            request = urllib2.Request(url)
53
            request.add_header('Accept','text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
54
            request.add_header('Accept-Language','en-US,en;q=0.8,hi;q=0.6')
55
            request.add_header('Connection','keep-alive')
56
            request.add_header('User-Agent','Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36')
57
 
58
            response = urllib2.urlopen(request)   
59
            response_data = response.read()
60
            response.close()
61
            try:
62
                page=response_data.decode("utf-8")
63
                soup = BeautifulSoup(page,convertEntities=BeautifulSoup.HTML_ENTITIES)
64
            except:
65
                soup = BeautifulSoup(response_data,convertEntities=BeautifulSoup.HTML_ENTITIES)
66
            if soup is None:
67
                raise
68
            return soup
69
        except Exception as e:
70
            print e
71
            print "Retrying"
72
            RETRY_COUNT = RETRY_COUNT + 1
73
 
74
 
75
def scrapeBestSellerMobiles():
76
    global bestSellers
77
    rank = 0
78
    for i in [1, 21, 41, 61, 81]:
79
        url = "http://www.flipkart.com/mobiles/~bestsellers/pr?p[]=sort=popularity&sid=tyy,4io&start=%d&ajax=true" %(i)
80
        soup = getSoupObject(url)
81
        product_divs = soup.findAll('div',{'class':re.compile('.*browse-product')})
82
        for x in product_divs:
83
            rank  = rank +1
84
            print rank,
85
            print '\t',
86
            print x['data-pid']
14379 kshitij.so 87
            r_info = __RankInfo(x['data-pid'].strip(),rank, None)
13754 kshitij.so 88
            bestSellers.append(r_info)
89
 
90
def scrapeBestSellerTablets():
91
    global bestSellers
92
    bestSellers = []
93
    rank = 0
94
    for i in [1, 21, 41, 61, 81]:
95
        url = "http://www.flipkart.com/tablets/~bestsellers/pr?p[]=sort=popularity&sid=tyy,hry&start=%d&ajax=true" %(i)
96
        soup = getSoupObject(url)
97
        product_divs = soup.findAll('div',{'class':re.compile('.*browse-product')})
98
        for x in product_divs:
99
            rank  = rank +1
100
            print rank,
101
            print '\t',
102
            print x['data-pid']
14379 kshitij.so 103
            r_info = __RankInfo(x['data-pid'].strip(),rank, None)
13754 kshitij.so 104
            bestSellers.append(r_info)
105
 
14379 kshitij.so 106
def commitBestSellers(category):
107
    global exceptionList
13754 kshitij.so 108
    for x in bestSellers:
109
        print x.rank,
110
        print '\t',
111
        print x.identifier,
112
        col = get_mongo_connection().Catalog.MasterData.find({'identifier':x.identifier.strip()})
113
        print "count sku",
114
        print '\t',
14379 kshitij.so 115
        if len(list(col)) == 0:
116
            x.category = category
117
            exceptionList.append(x)
118
        else:
119
            get_mongo_connection().Catalog.MasterData.update({'identifier':x.identifier.strip()}, {'$set' : {'rank':x.rank,'updatedOn':to_java_date(now)}}, multi=True)
13754 kshitij.so 120
 
121
def resetRanks(category):
13828 kshitij.so 122
    oldRankedItems = get_mongo_connection().Catalog.MasterData.find({'rank':{'$gt':0},'source_id':2,'category':category})
123
    for item in oldRankedItems:
124
        get_mongo_connection().Catalog.MasterData.update({'_id':item['_id']}, {'$set' : {'rank':0,'updatedOn':to_java_date(now)}}, multi=True)
14379 kshitij.so 125
 
126
def sendEmail():
127
    message="""<html>
128
            <body>
129
            <h3>Flipkart Best Sellers not in master</h3>
130
            <table border="1" style="width:100%;">
131
            <thead>
132
            <tr><th>Identifier</th>
133
            <th>Category</th>
134
            <th>Rank</th>
135
            </tr></thead>
136
            <tbody>"""
137
    for item in exceptionList:
138
        message+="""<tr>
139
        <td style="text-align:center">"""+(item.identifier)+"""</td>
140
        <td style="text-align:center">"""+(item.category)+"""</td>
141
        <td style="text-align:center">"""+str(item.rank)+"""</td>
142
        </tr>"""
143
    message+="""</tbody></table></body></html>"""
144
    print message
145
    #recipients = ['kshitij.sood@saholic.com']
146
    recipients = ['rajneesh.arora@saholic.com','kshitij.sood@saholic.com','chaitnaya.vats@saholic.com','manoj.kumar@saholic.com']
147
    msg = MIMEMultipart()
148
    msg['Subject'] = "Flipkart Best Sellers" + ' - ' + str(datetime.now())
149
    msg['From'] = ""
150
    msg['To'] = ",".join(recipients)
151
    msg.preamble = "Flipkart Best Sellers" + ' - ' + str(datetime.now())
152
    html_msg = MIMEText(message, 'html')
153
    msg.attach(html_msg)
154
 
155
    smtpServer = smtplib.SMTP('localhost')
156
    smtpServer.set_debuglevel(1)
157
    sender = 'dtr@shop2020.in'
158
    try:
159
        smtpServer.sendmail(sender, recipients, msg.as_string())
160
        print "Successfully sent email"
161
    except:
162
        print "Error: unable to send email."
13754 kshitij.so 163
 
164
def main():
165
    scrapeBestSellerMobiles()
166
    if len(bestSellers) > 0:
167
        resetRanks('Mobiles')
14379 kshitij.so 168
        commitBestSellers('MOBILES')
13754 kshitij.so 169
    scrapeBestSellerTablets()
170
    if len(bestSellers) > 0:
171
        resetRanks('Tablets')
14379 kshitij.so 172
        commitBestSellers('TABLETS')
173
    sendEmail()
13754 kshitij.so 174
 
175
if __name__=='__main__':
176
    main()