Subversion Repositories SmartDukaan

Rev

Rev 14380 | Rev 19240 | 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
18284 kshitij.so 5
from dtr.utils.utils import to_java_date, fetchResponseUsingProxy
13828 kshitij.so 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
18284 kshitij.so 11
from dtr.utils.utils import fetchResponseUsingProxy
13754 kshitij.so 12
 
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:
18284 kshitij.so 40
 
13754 kshitij.so 41
            print e
42
            return None
43
    return con
44
 
45
def getSoupObject(url):
46
    print "Getting soup object for"
47
    print url
18284 kshitij.so 48
    soup = None
49
    response_data = fetchResponseUsingProxy(url)
50
    print response_data
51
    try:
52
        page=response_data.decode("utf-8")
53
        soup = BeautifulSoup(page,convertEntities=BeautifulSoup.HTML_ENTITIES)
54
    except:
55
        soup = BeautifulSoup(response_data,convertEntities=BeautifulSoup.HTML_ENTITIES)
56
    return soup
13754 kshitij.so 57
 
58
def scrapeBestSellerMobiles():
59
    global bestSellers
60
    rank = 0
61
    for i in [1, 21, 41, 61, 81]:
62
        url = "http://www.flipkart.com/mobiles/~bestsellers/pr?p[]=sort=popularity&sid=tyy,4io&start=%d&ajax=true" %(i)
63
        soup = getSoupObject(url)
64
        product_divs = soup.findAll('div',{'class':re.compile('.*browse-product')})
65
        for x in product_divs:
66
            rank  = rank +1
67
            print rank,
68
            print '\t',
69
            print x['data-pid']
14379 kshitij.so 70
            r_info = __RankInfo(x['data-pid'].strip(),rank, None)
13754 kshitij.so 71
            bestSellers.append(r_info)
72
 
73
def scrapeBestSellerTablets():
74
    global bestSellers
75
    bestSellers = []
76
    rank = 0
77
    for i in [1, 21, 41, 61, 81]:
78
        url = "http://www.flipkart.com/tablets/~bestsellers/pr?p[]=sort=popularity&sid=tyy,hry&start=%d&ajax=true" %(i)
79
        soup = getSoupObject(url)
80
        product_divs = soup.findAll('div',{'class':re.compile('.*browse-product')})
81
        for x in product_divs:
82
            rank  = rank +1
83
            print rank,
84
            print '\t',
85
            print x['data-pid']
14379 kshitij.so 86
            r_info = __RankInfo(x['data-pid'].strip(),rank, None)
13754 kshitij.so 87
            bestSellers.append(r_info)
88
 
14379 kshitij.so 89
def commitBestSellers(category):
90
    global exceptionList
13754 kshitij.so 91
    for x in bestSellers:
92
        print x.rank,
93
        print '\t',
94
        print x.identifier,
95
        col = get_mongo_connection().Catalog.MasterData.find({'identifier':x.identifier.strip()})
96
        print "count sku",
97
        print '\t',
14379 kshitij.so 98
        if len(list(col)) == 0:
99
            x.category = category
100
            exceptionList.append(x)
101
        else:
102
            get_mongo_connection().Catalog.MasterData.update({'identifier':x.identifier.strip()}, {'$set' : {'rank':x.rank,'updatedOn':to_java_date(now)}}, multi=True)
13754 kshitij.so 103
 
104
def resetRanks(category):
13828 kshitij.so 105
    oldRankedItems = get_mongo_connection().Catalog.MasterData.find({'rank':{'$gt':0},'source_id':2,'category':category})
106
    for item in oldRankedItems:
107
        get_mongo_connection().Catalog.MasterData.update({'_id':item['_id']}, {'$set' : {'rank':0,'updatedOn':to_java_date(now)}}, multi=True)
14379 kshitij.so 108
 
109
def sendEmail():
110
    message="""<html>
111
            <body>
112
            <h3>Flipkart Best Sellers not in master</h3>
113
            <table border="1" style="width:100%;">
114
            <thead>
115
            <tr><th>Identifier</th>
116
            <th>Category</th>
117
            <th>Rank</th>
118
            </tr></thead>
119
            <tbody>"""
120
    for item in exceptionList:
121
        message+="""<tr>
122
        <td style="text-align:center">"""+(item.identifier)+"""</td>
123
        <td style="text-align:center">"""+(item.category)+"""</td>
124
        <td style="text-align:center">"""+str(item.rank)+"""</td>
125
        </tr>"""
126
    message+="""</tbody></table></body></html>"""
127
    print message
18284 kshitij.so 128
    recipients = ['kshitij.sood@saholic.com']
129
    #recipients = ['rajneesh.arora@saholic.com','kshitij.sood@saholic.com','chaitnaya.vats@saholic.com','manoj.kumar@saholic.com']
14379 kshitij.so 130
    msg = MIMEMultipart()
131
    msg['Subject'] = "Flipkart Best Sellers" + ' - ' + str(datetime.now())
132
    msg['From'] = ""
133
    msg['To'] = ",".join(recipients)
134
    msg.preamble = "Flipkart Best Sellers" + ' - ' + str(datetime.now())
135
    html_msg = MIMEText(message, 'html')
136
    msg.attach(html_msg)
137
 
138
    smtpServer = smtplib.SMTP('localhost')
139
    smtpServer.set_debuglevel(1)
140
    sender = 'dtr@shop2020.in'
141
    try:
142
        smtpServer.sendmail(sender, recipients, msg.as_string())
143
        print "Successfully sent email"
144
    except:
145
        print "Error: unable to send email."
13754 kshitij.so 146
 
147
def main():
148
    scrapeBestSellerMobiles()
149
    if len(bestSellers) > 0:
150
        resetRanks('Mobiles')
14379 kshitij.so 151
        commitBestSellers('MOBILES')
13754 kshitij.so 152
    scrapeBestSellerTablets()
153
    if len(bestSellers) > 0:
154
        resetRanks('Tablets')
14379 kshitij.so 155
        commitBestSellers('TABLETS')
156
    sendEmail()
13754 kshitij.so 157
 
158
if __name__=='__main__':
159
    main()