Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
12256 kshitij.so 1
from elixir import session
12268 kshitij.so 2
from shop2020.config.client.ConfigClient import ConfigClient
12256 kshitij.so 3
from sqlalchemy.sql import asc
4
from sqlalchemy.sql.expression import or_
5
from shop2020.utils.daemon import Daemon
6
import optparse
7
import sys
8
import threading
9
import urllib2
10
import mechanize
11
import cookielib
12
import time
13
import requests as httpRequest
14
import simplejson as json
15
from shop2020.model.v1.catalog.impl import DataService
16
from shop2020.model.v1.catalog.script import FlipkartScraper, AmazonScraper, SellerCentralScraper
17
from operator import itemgetter
18
from shop2020.model.v1.catalog.impl.DataService import CompetitorPricing, CompetitorPricingRequest, \
12272 kshitij.so 19
SnapdealItem, FlipkartItem
20
import gc 
12256 kshitij.so 21
 
12268 kshitij.so 22
config_client = ConfigClient()
23
host = config_client.get_property('staging_hostname')
24
DataService.initialize(db_hostname=host)
12256 kshitij.so 25
 
26
class CompetitorScraping(Daemon):
27
    def __init__(self, logfile='/var/log/services/competitorScraping.log', pidfile='/var/run/competitor-scraper.pid'):
28
        Daemon.__init__(self, pidfile, stdout=logfile, stderr=logfile)
29
 
30
    def run(self):
31
        start()
32
 
33
def start():
34
    try:
35
        while True:
36
            requests = session.query(CompetitorPricingRequest).filter(or_(CompetitorPricingRequest.isProcessed==False,CompetitorPricingRequest.isProcessed==None)).order_by(asc(CompetitorPricingRequest.requestId)).all()
37
            if requests ==[] or requests is None:
38
                print "No new request to process, sleeeeeeping....."
12281 kshitij.so 39
                close_session()
40
                collected = gc.collect()
41
                print "Garbage collector: collected %d objects." % (collected)
12256 kshitij.so 42
                time.sleep(600)
43
            for request in requests:
44
                fetchDetails(request)
45
                request.isProcessed = True
46
                session.commit()
47
            close_session()
12279 kshitij.so 48
            collected = gc.collect()
49
            print "Garbage collector: collected %d objects." % (collected)
50
            requests = []
12256 kshitij.so 51
    except Exception as e:
52
        print e
53
        sys.exit(2)
54
 
55
def fetchDetails(request):
56
    login_url = "https://sellercentral.amazon.in/gp/homepage.html"
57
    br = login(login_url)
58
    items = session.query(CompetitorPricing).filter(CompetitorPricing.competitorPricing_requestId==request.requestId).all()
59
    print items
60
    snapdeal, flipkart, amazon =[],[],[]
61
    for item in items:
62
        if item.snapdealScraping:
63
            snapdeal.append(item)
64
        if item.flipkartScraping:
65
            flipkart.append(item)
66
        if item.amazonScraping:
67
            amazon.append(item)
68
    threads = []
69
    t1 = threading.Thread(target=scrapSnapdeal, args = (snapdeal,))
70
    t1.daemon = True
71
    t1.start()
72
    t2 = threading.Thread(target=scrapFlipkart, args = (flipkart,))
73
    t2.daemon = True
74
    t2.start()
12278 kshitij.so 75
    t3 = threading.Thread(target=scrapAmazon, args = (amazon,br))
76
    t3.daemon = True
77
    t3.start()
12256 kshitij.so 78
    threads.append(t1)
79
    threads.append(t2)
80
    threads.append(t3)
81
    for th in threads:
82
        th.join()
12284 kshitij.so 83
    br,t1,t2,t3 =None,None,None,None
84
    items[:],snapdeal[:],flipkart[:],amazon[:],threads[:]=[],[],[],[],[]
12256 kshitij.so 85
 
86
def scrapSnapdeal(snapdealItems):
87
    for snapdealItem in snapdealItems:
88
        sdItem = SnapdealItem.get_by(item_id=snapdealItem.item_id)
89
        if sdItem is None:
90
            continue
91
        try:
92
            url="http://www.snapdeal.com/acors/json/gvbps?supc=%s&catId=91&sort=sellingPrice"%(sdItem.supc)
93
            print url
94
            time.sleep(1)
95
            req = urllib2.Request(url)
96
            response = urllib2.urlopen(req)
97
            json_input = response.read()
98
            vendorInfo = json.loads(json_input)
99
            lowestSp, iterator, ourInventory, lowestSellerInventory,ourSp,ourOfferPrice,lowestSp,lowestOfferPrice   = (0,)*8
100
            lowestSellerName = ''
101
            for vendor in vendorInfo:
102
                if iterator == 0:
103
                    lowestSellerName = vendor['vendorDisplayName']
104
                    try:
105
                        lowestSp = vendor['sellingPriceBefIntCashBack']
106
                    except:
107
                        lowestSp = vendor['sellingPrice']
108
                    lowestOfferPrice = vendor['sellingPrice']
109
                    lowestSellerInventory = vendor['buyableInventory']
110
 
111
                if vendor['vendorDisplayName'] == 'MobilesnMore':
112
                    ourInventory = vendor['buyableInventory']
113
                    try:
114
                        ourSp = vendor['sellingPriceBefIntCashBack']
115
                    except:
116
                        ourSp = vendor['sellingPrice']
117
                    ourOfferPrice = vendor['sellingPrice']
118
                iterator+=1
119
        except:
120
            continue
121
        snapdealItem.ourSnapdealPrice = ourSp
122
        snapdealItem.ourSnapdealOfferPrice = ourOfferPrice
123
        snapdealItem.ourSnapdealInventory = ourInventory
124
        snapdealItem.lowestSnapdealPrice = lowestSp
125
        snapdealItem.lowestSnapdealOfferPrice = lowestOfferPrice
126
        snapdealItem.lowestSnapdealSeller = lowestSellerName 
127
        snapdealItem.lowestSnapdealSellerInventory = lowestSellerInventory  
128
 
129
def scrapFlipkart(flipkartItems):
12276 kshitij.so 130
    scraperFk = FlipkartScraper.FlipkartScraper()
12256 kshitij.so 131
    for flipkartItem in flipkartItems:
132
        fkItem = FlipkartItem.get_by(item_id=flipkartItem.item_id)
133
        if fkItem is None:
134
            continue
135
        try:
136
            url = "http://www.flipkart.com/ps/%s"%(fkItem.flipkartSerialNumber)
137
            vendorsData = scraperFk.read(url)
138
            sortedVendorsData = []
139
            sortedVendorsData = sorted(vendorsData, key=itemgetter('sellingPrice'))
140
            lowestSellerSp, iterator, ourSp = (0,)*3
141
            lowestSellerName = ''
142
            for data in sortedVendorsData:
143
                if iterator == 0:
144
                    lowestSellerName = data['sellerName']
145
                    lowestSellerSp = data['sellingPrice']
146
 
147
                if data['sellerName'] == 'Saholic':
148
                    ourSp = data['sellingPrice']
149
 
150
                iterator+=1
151
        except:
152
            continue
153
 
154
        try:
155
            request_url = "https://api.flipkart.net/sellers/skus/%s/listings"%(str(fkItem.flipkartSerialNumber))
156
            r = httpRequest.get(request_url, auth=('m2z93iskuj81qiid', '0c7ab6a5-98c0-4cdc-8be3-72c591e0add4'))
157
            print "Inventory info",r.json()
158
            stock_count = int((r.json()['attributeValues'])['stock_count'])
159
        except:
160
            stock_count = 0
161
        finally:
162
                r={}
163
        flipkartItem.ourFlipkartPrice = ourSp
164
        flipkartItem.ourFlipkartInventory = stock_count
165
        flipkartItem.lowestFlipkartPrice = lowestSellerSp
166
        flipkartItem.lowestFlipkartSeller =  lowestSellerName
12283 kshitij.so 167
    scraperFk = None
12256 kshitij.so 168
 
169
 
170
def close_session():
171
    if session.is_active:
172
        print "session is active. closing it."
173
        session.close()
174
 
175
def scrapAmazon(amazonItems,br):
12277 kshitij.so 176
    print "Inside amazonitems ",amazonItems
177
    print "len amazon items ",len(amazonItems)
178
    time.sleep(5)
12276 kshitij.so 179
    sc = SellerCentralScraper.SellerCentralScraper()
12285 kshitij.so 180
    scraperAmazon = AmazonScraper.AmazonScraper()
12256 kshitij.so 181
    for amazonItem in amazonItems:
182
        skuUrlMfn = "https://sellercentral.amazon.in/myi/search/ProductSummary?keyword=%d" %(amazonItem.item_id)
183
        skuUrlFba =  "https://sellercentral.amazon.in/myi/search/ProductSummary?keyword=FBA%d" %(amazonItem.item_id)
184
        try:
185
            asin, mfnInventory, mfnPrice= sc.requestSku(br, skuUrlMfn)
186
            fbaAsin, fbaInventory, fbaPrice= sc.requestSku(br, skuUrlFba)
187
        except Exception as e:
188
            print e
189
            print "Unable to fetch details from Seller Central for ",amazonItem.item_id
190
            continue
191
        try:
192
            if len(asin)==0 and len(fbaAsin)==0:
193
                print "No asin found for ",amazonItem.item_id
194
                continue
195
            if len(asin)==0:
196
                asin=fbaAsin
197
            url = "http://www.amazon.in/gp/offer-listing/%s/ref=olp_sort_ps"%(asin)
198
            scraperAmazon.read(url,True)
199
            lowestSp,lowestSeller = scraperAmazon.createData()
200
            amazonItem.lowestAmazonPrice = lowestSp
201
 
202
            print "Details of Item id ",amazonItem.item_id
203
            print "ASIN ",asin
204
            print "MFN INVENTORY ",mfnInventory
205
            print "FBA INVENTORY ",fbaInventory
206
            print "MFN PRICE ",mfnPrice
207
            print "FBA PRICE ",fbaPrice
208
            print "Lowest Seller SP ",lowestSp
209
            print "LOWEST SELLER NAME ",lowestSeller
210
 
12271 kshitij.so 211
            amazonItem.ourMfnPrice = float(str(mfnPrice).replace("Rs.","").replace(",",""))
212
            amazonItem.ourFbaPrice = float(str(fbaPrice).replace("Rs.","").replace(",",""))
12256 kshitij.so 213
            amazonItem.ourMfnInventory = int(mfnInventory)
214
            amazonItem.ourFbaInventory = int(fbaInventory)
215
            amazonItem.lowestAmazonPrice = float(lowestSp)
216
            amazonItem.lowestAmazonSeller = lowestSeller
217
 
218
        except Exception as e:
219
            print e
220
            print "Unable to fetch details from Amazon Listing page for ",amazonItem.item_id
221
            continue
12283 kshitij.so 222
    sc =None
12285 kshitij.so 223
    scraperAmazon = None
12256 kshitij.so 224
 
225
def getBrowserObject():
226
        br = mechanize.Browser(factory=mechanize.RobustFactory())
227
        cj = cookielib.LWPCookieJar()
228
        br.set_cookiejar(cj)
229
        br.set_handle_equiv(True)
230
        br.set_handle_redirect(True)
231
        br.set_handle_referer(True)
232
        br.set_handle_robots(False)
233
        br.set_debug_http(False)
234
        br.set_debug_redirects(False)
235
        br.set_debug_responses(False)
236
 
237
        br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
238
 
239
        br.addheaders = [('User-agent','Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11'),
240
                         ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'),
241
                         ('Accept-Encoding', 'gzip,deflate,sdch'),                  
242
                         ('Accept-Language', 'en-US,en;q=0.8'),                     
243
                         ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.3')]
244
        return br
245
 
246
def ungzipResponse(r,b):
247
    headers = r.info()
248
    if headers['Content-Encoding']=='gzip':
249
        import gzip
250
        print "********************"
251
        print "Deflating gzip response"
252
        print "********************"
253
        gz = gzip.GzipFile(fileobj=r, mode='rb')
254
        html = gz.read()
255
        gz.close()
256
        headers["Content-type"] = "text/html; charset=utf-8"
257
        r.set_data( html )
258
        b.set_response(r)
259
 
260
 
261
def login(url):
262
    br = getBrowserObject()
263
    br.open(url)
264
    response = br.open(url)
265
    ungzipResponse(response, br)
266
    #html = response.read()
267
    #print html
268
    br.select_form(name="signinWidget")
269
    br.form['username'] = "kshitij.sood@saholic.com"
270
    br.form['password'] = "pioneer"
271
    response = br.submit()
272
    print "********************"
273
    print "Attempting to Login"
274
    print "********************"
275
    #ungzipResponse(response, br)
276
    return br
277
 
278
 
279
 
280
if __name__ == "__main__":
281
    parser = optparse.OptionParser()
282
    parser.add_option("-l", "--logfile", dest="logfile",
283
                      type="string",
284
                      help="Log all output to LOG_FILE",
285
                      )
286
    parser.add_option("-i", "--pidfile", dest="pidfile",
287
                      type="string",
288
                      help="Write the PID to pidfile")
289
    (options, args) = parser.parse_args()
290
    daemon = CompetitorScraping(options.logfile, options.pidfile)
291
    if len(args) == 0:
292
        daemon.run()
293
    elif len(args) == 1:
294
        if 'start' == args[0]:
295
            daemon.start()
296
        elif 'stop' == args[0]:
297
            daemon.stop()
298
        elif 'restart' == args[0]:
299
            daemon.restart()
300
        else:
301
            print "Unknown command"
302
            sys.exit(2)
303
        sys.exit(0)
304
    else:
305
        print "usage: %s start|stop|restart" % sys.argv[0]
306
        sys.exit(2)