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 range(1,6):
62
        aboveFoldUrl = "http://www.amazon.in/gp/bestsellers/electronics/1389432031/ref=zg_bs_1389432031_pg_%d?ie=UTF8&pg=%d&ajax=1&isAboveTheFold=1" %(i,i) 
63
        belowFoldUrl = "http://www.amazon.in/gp/bestsellers/electronics/1389432031/ref=zg_bs_1389432031_pg_%d?ie=UTF8&pg=%d&ajax=1&isAboveTheFold=0" %(i,i)
64
        above_soup = getSoupObject(aboveFoldUrl)
65
        below_soup = getSoupObject(belowFoldUrl)
66
        for x in above_soup.findAll('div',{'class':'zg_itemImmersion'}):
67
            am_url =  x.find('div',{'class':'zg_title'}).find('a')['href']
68
            identifier =  (re.search(asin_regex, am_url)).group(1)
69
            rank = rank + 1
70
            r_info = __RankInfo(identifier,rank)
71
            bestSellers.append(r_info)
72
        for x in below_soup.findAll('div',{'class':'zg_itemImmersion'}):
73
            am_url =  x.find('div',{'class':'zg_title'}).find('a')['href']
74
            identifier =  (re.search(asin_regex, am_url)).group(1)
75
            rank = rank + 1
76
            r_info = __RankInfo(identifier,rank)
77
            bestSellers.append(r_info)
78
 
79
def commitBestSellers():
80
    print "Rank",
81
    print '\t',
82
    print 'Identifier'
83
    for x in bestSellers:
84
        print x.rank,
85
        print '\t',
86
        print x.identifier,
87
        col = get_mongo_connection().Catalog.MasterData.find({'identifier':x.identifier.strip()})
88
        print "count sku",
89
        print '\t',
90
        print len(list(col))
91
        get_mongo_connection().Catalog.MasterData.update({'identifier':x.identifier.strip()}, {'$set' : {'rank':x.rank}}, multi=True)
92
 
93
def scrapeBestSellerTablets():
94
    global bestSellers
95
    bestSellers = []
96
    rank = 0
97
    for i in range(1,6):
98
        aboveFoldUrl = "http://www.amazon.in/gp/bestsellers/electronics/1375458031/ref=zg_bs_1375458031_pg_%d?ie=UTF8&pg=%d&ajax=1" %(i,i) 
99
        belowFoldUrl = "http://www.amazon.in/gp/bestsellers/electronics/1375458031/ref=zg_bs_1375458031_pg_%d?ie=UTF8&pg=%d&ajax=1&isAboveTheFold=0" %(i,i)
100
        above_soup = getSoupObject(aboveFoldUrl)
101
        below_soup = getSoupObject(belowFoldUrl)
102
        for x in above_soup.findAll('div',{'class':'zg_itemImmersion'}):
103
            am_url =  x.find('div',{'class':'zg_title'}).find('a')['href']
104
            identifier =  (re.search(asin_regex, am_url)).group(1)
105
            rank = rank + 1
106
            r_info = __RankInfo(identifier,rank)
107
            bestSellers.append(r_info)
108
        for x in below_soup.findAll('div',{'class':'zg_itemImmersion'}):
109
            am_url =  x.find('div',{'class':'zg_title'}).find('a')['href']
110
            identifier =  (re.search(asin_regex, am_url)).group(1)
111
            rank = rank + 1
112
            r_info = __RankInfo(identifier,rank)
113
            bestSellers.append(r_info)
114
 
115
def resetRanks(category):
116
    get_mongo_connection().Catalog.MasterData.update({'category':category,'source_id':1}, {'$set' : {'rank':0}}, multi=True)
117
 
118
def main():
119
    scrapeBestSellerMobiles()
120
    if len(bestSellers) > 0:
121
        resetRanks('Mobiles')
122
        commitBestSellers()
123
    scrapeBestSellerTablets()
124
    if len(bestSellers) > 0:
125
        resetRanks('Tablets')
126
        commitBestSellers()
127
 
128
if __name__=='__main__':
129
    main()