Subversion Repositories SmartDukaan

Rev

Rev 13828 | Rev 14257 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
13828 kshitij.so 1
import urllib
2
import urllib2
3
from BeautifulSoup import BeautifulSoup
4
import pymongo
5
import re
6
from dtr.utils.utils import to_java_date
7
from datetime import datetime
8
 
9
con = None
10
bestSellers = []
11
now = datetime.now()
12
mobUrl = "http://www.saholic.com/mobile-phone/10006"
13
tabUrl = "http://www.saholic.com/all-tablets/10010"
14
 
15
class __RankInfo:
16
 
17
    def __init__(self, identifier, rank):
18
        self.identifier = identifier
19
        self.rank  = rank
20
 
21
def get_mongo_connection(host='localhost', port=27017):
22
    global con
23
    if con is None:
24
        print "Establishing connection %s host and port %d" %(host,port)
25
        try:
26
            con = pymongo.MongoClient(host, port)
27
        except Exception, e:
28
            print e
29
            return None
30
    return con
31
 
32
def getSoupObject(url,data):
33
    print "Getting soup object for"
34
    global RETRY_COUNT
35
    RETRY_COUNT = 1 
36
    while RETRY_COUNT < 10:
37
        try:
38
            soup = None
39
            request = urllib2.Request(url,data)
40
            request.add_header('Accept','text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
41
            request.add_header('Accept-Language','en-US,en;q=0.8,hi;q=0.6')
42
            request.add_header('Connection','keep-alive')
43
            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')
44
 
45
            response = urllib2.urlopen(request)   
46
            response_data = response.read()
47
            response.close()
48
            try:
49
                page=response_data.decode("utf-8")
50
                soup = BeautifulSoup(page,convertEntities=BeautifulSoup.HTML_ENTITIES)
51
            except:
52
                soup = BeautifulSoup(response_data,convertEntities=BeautifulSoup.HTML_ENTITIES)
53
            if soup is None:
54
                raise
55
            return soup
56
        except Exception as e:
57
            print e
58
            print "Retrying"
59
            RETRY_COUNT = RETRY_COUNT + 1
60
 
61
def scrapeBestSellerMobiles():
62
    global bestSellers
63
    rank = 1
64
    for i in range(1,6):
65
        query_args = { 'fq':'F_50028:In Stock', 'page':i }
66
        data = urllib.urlencode(query_args)
67
        soup = getSoupObject(mobUrl,data)
68
        titleTags = soup.findAll('div',{'class':'title'})
69
        for titleTag in titleTags:
70
            print titleTag.find('a').text
71
            identifier = getSaholicIdentifier(titleTag.find('a')['href'])
72
            r_info = __RankInfo(str(identifier), rank)
73
            bestSellers.append(r_info)
74
            rank = rank + 1
75
 
76
def scrapeBestSellerTablets():
77
    global bestSellers
78
    bestSellers = [] 
79
    rank = 1
80
    for i in range(1,6):
81
        query_args = { 'fq':'F_50028:In Stock', 'page':i }
82
        data = urllib.urlencode(query_args)
83
        soup = getSoupObject(tabUrl, data)
84
        titleTags = soup.findAll('div',{'class':'title'})
85
        for titleTag in titleTags:
86
            print titleTag.find('a').text
87
            identifier = getSaholicIdentifier(titleTag.find('a')['href'])
88
            r_info = __RankInfo(str(identifier), rank)
89
            bestSellers.append(r_info)
90
            rank = rank + 1
91
 
92
def getSaholicIdentifier(url):
93
    return url[url.rfind('-')+len('-'):]
94
 
95
def resetRanks(category):
96
    oldRankedItems = get_mongo_connection().Catalog.MasterData.find({'rank':{'$gt':0},'source_id':4,'category':category})
97
    for item in oldRankedItems:
98
        print item['_id']
99
        get_mongo_connection().Catalog.MasterData.update({'_id':item['_id']}, {'$set' : {'rank':0,'updatedOn':to_java_date(now)}}, multi=True)
100
 
101
def commitBestSellers():
102
    print "Rank",
103
    print '\t',
104
    print 'Identifier'
105
    for x in bestSellers:
106
        print x.rank,
107
        print '\t',
14057 kshitij.so 108
        print x.identifier,
13828 kshitij.so 109
        col = get_mongo_connection().Catalog.MasterData.find({'identifier':x.identifier})
110
        print "count sku",
111
        print '\t',
112
        print len(list(col))
113
        get_mongo_connection().Catalog.MasterData.update({'identifier':x.identifier,'source_id':4}, {'$set' : {'rank':x.rank,'updatedOn':to_java_date(now)}}, multi=True)
114
 
115
 
116
 
117
def main():
118
    scrapeBestSellerMobiles()
119
    if len(bestSellers) > 0:
120
        resetRanks('Mobiles')
121
        commitBestSellers()
122
    scrapeBestSellerTablets()
123
    if len(bestSellers) > 0:
124
        resetRanks('Tablets')
125
        commitBestSellers()
126
if __name__=='__main__':
127
    main()