Subversion Repositories SmartDukaan

Rev

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