Subversion Repositories SmartDukaan

Rev

Rev 12281 | Rev 12284 | 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()
83
 
12272 kshitij.so 84
 
12256 kshitij.so 85
def scrapSnapdeal(snapdealItems):
86
    for snapdealItem in snapdealItems:
87
        sdItem = SnapdealItem.get_by(item_id=snapdealItem.item_id)
88
        if sdItem is None:
89
            continue
90
        try:
91
            url="http://www.snapdeal.com/acors/json/gvbps?supc=%s&catId=91&sort=sellingPrice"%(sdItem.supc)
92
            print url
93
            time.sleep(1)
94
            req = urllib2.Request(url)
95
            response = urllib2.urlopen(req)
96
            json_input = response.read()
97
            vendorInfo = json.loads(json_input)
98
            lowestSp, iterator, ourInventory, lowestSellerInventory,ourSp,ourOfferPrice,lowestSp,lowestOfferPrice   = (0,)*8
99
            lowestSellerName = ''
100
            for vendor in vendorInfo:
101
                if iterator == 0:
102
                    lowestSellerName = vendor['vendorDisplayName']
103
                    try:
104
                        lowestSp = vendor['sellingPriceBefIntCashBack']
105
                    except:
106
                        lowestSp = vendor['sellingPrice']
107
                    lowestOfferPrice = vendor['sellingPrice']
108
                    lowestSellerInventory = vendor['buyableInventory']
109
 
110
                if vendor['vendorDisplayName'] == 'MobilesnMore':
111
                    ourInventory = vendor['buyableInventory']
112
                    try:
113
                        ourSp = vendor['sellingPriceBefIntCashBack']
114
                    except:
115
                        ourSp = vendor['sellingPrice']
116
                    ourOfferPrice = vendor['sellingPrice']
117
                iterator+=1
118
        except:
119
            continue
120
        snapdealItem.ourSnapdealPrice = ourSp
121
        snapdealItem.ourSnapdealOfferPrice = ourOfferPrice
122
        snapdealItem.ourSnapdealInventory = ourInventory
123
        snapdealItem.lowestSnapdealPrice = lowestSp
124
        snapdealItem.lowestSnapdealOfferPrice = lowestOfferPrice
125
        snapdealItem.lowestSnapdealSeller = lowestSellerName 
126
        snapdealItem.lowestSnapdealSellerInventory = lowestSellerInventory  
127
 
128
def scrapFlipkart(flipkartItems):
12276 kshitij.so 129
    scraperFk = FlipkartScraper.FlipkartScraper()
12256 kshitij.so 130
    for flipkartItem in flipkartItems:
131
        fkItem = FlipkartItem.get_by(item_id=flipkartItem.item_id)
132
        if fkItem is None:
133
            continue
134
        try:
135
            url = "http://www.flipkart.com/ps/%s"%(fkItem.flipkartSerialNumber)
136
            vendorsData = scraperFk.read(url)
137
            sortedVendorsData = []
138
            sortedVendorsData = sorted(vendorsData, key=itemgetter('sellingPrice'))
139
            lowestSellerSp, iterator, ourSp = (0,)*3
140
            lowestSellerName = ''
141
            for data in sortedVendorsData:
142
                if iterator == 0:
143
                    lowestSellerName = data['sellerName']
144
                    lowestSellerSp = data['sellingPrice']
145
 
146
                if data['sellerName'] == 'Saholic':
147
                    ourSp = data['sellingPrice']
148
 
149
                iterator+=1
150
        except:
151
            continue
152
 
153
        try:
154
            request_url = "https://api.flipkart.net/sellers/skus/%s/listings"%(str(fkItem.flipkartSerialNumber))
155
            r = httpRequest.get(request_url, auth=('m2z93iskuj81qiid', '0c7ab6a5-98c0-4cdc-8be3-72c591e0add4'))
156
            print "Inventory info",r.json()
157
            stock_count = int((r.json()['attributeValues'])['stock_count'])
158
        except:
159
            stock_count = 0
160
        finally:
161
                r={}
162
        flipkartItem.ourFlipkartPrice = ourSp
163
        flipkartItem.ourFlipkartInventory = stock_count
164
        flipkartItem.lowestFlipkartPrice = lowestSellerSp
165
        flipkartItem.lowestFlipkartSeller =  lowestSellerName
12283 kshitij.so 166
    scraperFk = None
12256 kshitij.so 167
 
168
 
169
def close_session():
170
    if session.is_active:
171
        print "session is active. closing it."
172
        session.close()
173
 
174
def scrapAmazon(amazonItems,br):
12277 kshitij.so 175
    print "Inside amazonitems ",amazonItems
176
    print "len amazon items ",len(amazonItems)
177
    time.sleep(5)
12276 kshitij.so 178
    sc = SellerCentralScraper.SellerCentralScraper()
12256 kshitij.so 179
    for amazonItem in amazonItems:
180
        skuUrlMfn = "https://sellercentral.amazon.in/myi/search/ProductSummary?keyword=%d" %(amazonItem.item_id)
181
        skuUrlFba =  "https://sellercentral.amazon.in/myi/search/ProductSummary?keyword=FBA%d" %(amazonItem.item_id)
182
        try:
183
            print type(sc.requestSku(br, skuUrlMfn))
184
            asin, mfnInventory, mfnPrice= sc.requestSku(br, skuUrlMfn)
185
            fbaAsin, fbaInventory, fbaPrice= sc.requestSku(br, skuUrlFba)
186
        except Exception as e:
187
            print e
188
            print "Unable to fetch details from Seller Central for ",amazonItem.item_id
189
            continue
190
        scraperAmazon = AmazonScraper.AmazonScraper()
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
12256 kshitij.so 223
 
224
def getBrowserObject():
225
        br = mechanize.Browser(factory=mechanize.RobustFactory())
226
        cj = cookielib.LWPCookieJar()
227
        br.set_cookiejar(cj)
228
        br.set_handle_equiv(True)
229
        br.set_handle_redirect(True)
230
        br.set_handle_referer(True)
231
        br.set_handle_robots(False)
232
        br.set_debug_http(False)
233
        br.set_debug_redirects(False)
234
        br.set_debug_responses(False)
235
 
236
        br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
237
 
238
        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'),
239
                         ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'),
240
                         ('Accept-Encoding', 'gzip,deflate,sdch'),                  
241
                         ('Accept-Language', 'en-US,en;q=0.8'),                     
242
                         ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.3')]
243
        return br
244
 
245
def ungzipResponse(r,b):
246
    headers = r.info()
247
    if headers['Content-Encoding']=='gzip':
248
        import gzip
249
        print "********************"
250
        print "Deflating gzip response"
251
        print "********************"
252
        gz = gzip.GzipFile(fileobj=r, mode='rb')
253
        html = gz.read()
254
        gz.close()
255
        headers["Content-type"] = "text/html; charset=utf-8"
256
        r.set_data( html )
257
        b.set_response(r)
258
 
259
 
260
def login(url):
261
    br = getBrowserObject()
262
    br.open(url)
263
    response = br.open(url)
264
    ungzipResponse(response, br)
265
    #html = response.read()
266
    #print html
267
    br.select_form(name="signinWidget")
268
    br.form['username'] = "kshitij.sood@saholic.com"
269
    br.form['password'] = "pioneer"
270
    response = br.submit()
271
    print "********************"
272
    print "Attempting to Login"
273
    print "********************"
274
    #ungzipResponse(response, br)
275
    return br
276
 
277
 
278
 
279
if __name__ == "__main__":
280
    parser = optparse.OptionParser()
281
    parser.add_option("-l", "--logfile", dest="logfile",
282
                      type="string",
283
                      help="Log all output to LOG_FILE",
284
                      )
285
    parser.add_option("-i", "--pidfile", dest="pidfile",
286
                      type="string",
287
                      help="Write the PID to pidfile")
288
    (options, args) = parser.parse_args()
289
    daemon = CompetitorScraping(options.logfile, options.pidfile)
290
    if len(args) == 0:
291
        daemon.run()
292
    elif len(args) == 1:
293
        if 'start' == args[0]:
294
            daemon.start()
295
        elif 'stop' == args[0]:
296
            daemon.stop()
297
        elif 'restart' == args[0]:
298
            daemon.restart()
299
        else:
300
            print "Unknown command"
301
            sys.exit(2)
302
        sys.exit(0)
303
    else:
304
        print "usage: %s start|stop|restart" % sys.argv[0]
305
        sys.exit(2)