Subversion Repositories SmartDukaan

Rev

Rev 13828 | Go to most recent revision | Details | 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
5
 
6
asin_regex = r'/([A-Z0-9]{10})'
7
con = None
8
bestSellers = []
9
 
10
class __RankInfo:
11
 
12
    def __init__(self, identifier, rank):
13
        self.identifier = identifier
14
        self.rank  = rank
15
 
16
def get_mongo_connection(host='localhost', port=27017):
17
    global con
18
    if con is None:
19
        print "Establishing connection %s host and port %d" %(host,port)
20
        try:
21
            con = pymongo.MongoClient(host, port)
22
        except Exception, e:
23
            print e
24
            return None
25
    return con
26
 
27
def getSoupObject(url):
28
    print "Getting soup object for"
29
    print url
30
    global RETRY_COUNT
31
    RETRY_COUNT = 1 
32
    while RETRY_COUNT < 10:
33
        try:
34
            soup = None
35
            request = urllib2.Request(url)
36
            request.add_header('Accept','text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
37
            request.add_header('Accept-Language','en-US,en;q=0.8,hi;q=0.6')
38
            request.add_header('Connection','keep-alive')
39
            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')
40
 
41
            response = urllib2.urlopen(request)   
42
            response_data = response.read()
43
            response.close()
44
            try:
45
                page=response_data.decode("utf-8")
46
                soup = BeautifulSoup(page,convertEntities=BeautifulSoup.HTML_ENTITIES)
47
            except:
48
                soup = BeautifulSoup(response_data,convertEntities=BeautifulSoup.HTML_ENTITIES)
49
            if soup is None:
50
                raise
51
            return soup
52
        except Exception as e:
53
            print e
54
            print "Retrying"
55
            RETRY_COUNT = RETRY_COUNT + 1
56
 
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']
70
            r_info = __RankInfo(x['data-pid'].strip(),rank)
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']
86
            r_info = __RankInfo(x['data-pid'].strip(),rank)
87
            bestSellers.append(r_info)
88
 
89
def commitBestSellers():
90
    for x in bestSellers:
91
        print x.rank,
92
        print '\t',
93
        print x.identifier,
94
        col = get_mongo_connection().Catalog.MasterData.find({'identifier':x.identifier.strip()})
95
        print "count sku",
96
        print '\t',
97
        print len(list(col))
98
        get_mongo_connection().Catalog.MasterData.update({'identifier':x.identifier.strip()}, {'$set' : {'rank':x.rank}}, multi=True)
99
 
100
def resetRanks(category):
101
    get_mongo_connection().Catalog.MasterData.update({'category':category,'source_id':2}, {'$set' : {'rank':0}}, multi=True)
102
 
103
def main():
104
    scrapeBestSellerMobiles()
105
    if len(bestSellers) > 0:
106
        resetRanks('Mobiles')
107
        commitBestSellers()
108
    scrapeBestSellerTablets()
109
    if len(bestSellers) > 0:
110
        resetRanks('Tablets')
111
        commitBestSellers()
112
 
113
if __name__=='__main__':
114
    main()