Subversion Repositories SmartDukaan

Rev

Rev 13828 | Rev 14379 | 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
13754 kshitij.so 8
 
9
con = None
14257 kshitij.so 10
parser = optparse.OptionParser()
11
parser.add_option("-m", "--m", dest="mongoHost",
12
                      default="localhost",
13
                      type="string", help="The HOST where the mongo server is running",
14
                      metavar="mongo_host")
15
 
16
(options, args) = parser.parse_args()
17
 
13754 kshitij.so 18
bestSellers = []
13828 kshitij.so 19
now = datetime.now()
13754 kshitij.so 20
 
21
class __RankInfo:
22
 
23
    def __init__(self, identifier, rank):
24
        self.identifier = identifier
25
        self.rank  = rank
26
 
14257 kshitij.so 27
def get_mongo_connection(host=options.mongoHost, port=27017):
13754 kshitij.so 28
    global con
29
    if con is None:
30
        print "Establishing connection %s host and port %d" %(host,port)
31
        try:
32
            con = pymongo.MongoClient(host, port)
33
        except Exception, e:
34
            print e
35
            return None
36
    return con
37
 
38
def getSoupObject(url):
39
    print "Getting soup object for"
40
    print url
41
    global RETRY_COUNT
42
    RETRY_COUNT = 1 
43
    while RETRY_COUNT < 10:
44
        try:
45
            soup = None
46
            request = urllib2.Request(url)
47
            request.add_header('Accept','text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
48
            request.add_header('Accept-Language','en-US,en;q=0.8,hi;q=0.6')
49
            request.add_header('Connection','keep-alive')
50
            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')
51
 
52
            response = urllib2.urlopen(request)   
53
            response_data = response.read()
54
            response.close()
55
            try:
56
                page=response_data.decode("utf-8")
57
                soup = BeautifulSoup(page,convertEntities=BeautifulSoup.HTML_ENTITIES)
58
            except:
59
                soup = BeautifulSoup(response_data,convertEntities=BeautifulSoup.HTML_ENTITIES)
60
            if soup is None:
61
                raise
62
            return soup
63
        except Exception as e:
64
            print e
65
            print "Retrying"
66
            RETRY_COUNT = RETRY_COUNT + 1
67
 
68
 
69
def scrapeBestSellerMobiles():
70
    global bestSellers
71
    rank = 0
72
    for i in [1, 21, 41, 61, 81]:
73
        url = "http://www.flipkart.com/mobiles/~bestsellers/pr?p[]=sort=popularity&sid=tyy,4io&start=%d&ajax=true" %(i)
74
        soup = getSoupObject(url)
75
        product_divs = soup.findAll('div',{'class':re.compile('.*browse-product')})
76
        for x in product_divs:
77
            rank  = rank +1
78
            print rank,
79
            print '\t',
80
            print x['data-pid']
81
            r_info = __RankInfo(x['data-pid'].strip(),rank)
82
            bestSellers.append(r_info)
83
 
84
def scrapeBestSellerTablets():
85
    global bestSellers
86
    bestSellers = []
87
    rank = 0
88
    for i in [1, 21, 41, 61, 81]:
89
        url = "http://www.flipkart.com/tablets/~bestsellers/pr?p[]=sort=popularity&sid=tyy,hry&start=%d&ajax=true" %(i)
90
        soup = getSoupObject(url)
91
        product_divs = soup.findAll('div',{'class':re.compile('.*browse-product')})
92
        for x in product_divs:
93
            rank  = rank +1
94
            print rank,
95
            print '\t',
96
            print x['data-pid']
97
            r_info = __RankInfo(x['data-pid'].strip(),rank)
98
            bestSellers.append(r_info)
99
 
100
def commitBestSellers():
101
    for x in bestSellers:
102
        print x.rank,
103
        print '\t',
104
        print x.identifier,
105
        col = get_mongo_connection().Catalog.MasterData.find({'identifier':x.identifier.strip()})
106
        print "count sku",
107
        print '\t',
108
        print len(list(col))
13828 kshitij.so 109
        get_mongo_connection().Catalog.MasterData.update({'identifier':x.identifier.strip()}, {'$set' : {'rank':x.rank,'updatedOn':to_java_date(now)}}, multi=True)
13754 kshitij.so 110
 
111
def resetRanks(category):
13828 kshitij.so 112
    oldRankedItems = get_mongo_connection().Catalog.MasterData.find({'rank':{'$gt':0},'source_id':2,'category':category})
113
    for item in oldRankedItems:
114
        get_mongo_connection().Catalog.MasterData.update({'_id':item['_id']}, {'$set' : {'rank':0,'updatedOn':to_java_date(now)}}, multi=True)
13754 kshitij.so 115
 
116
def main():
117
    scrapeBestSellerMobiles()
118
    if len(bestSellers) > 0:
119
        resetRanks('Mobiles')
120
        commitBestSellers()
121
    scrapeBestSellerTablets()
122
    if len(bestSellers) > 0:
123
        resetRanks('Tablets')
124
        commitBestSellers()
125
 
126
if __name__=='__main__':
127
    main()