Subversion Repositories SmartDukaan

Rev

Rev 12279 | Rev 12283 | 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
166
 
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
222
 
223
def getBrowserObject():
224
        br = mechanize.Browser(factory=mechanize.RobustFactory())
225
        cj = cookielib.LWPCookieJar()
226
        br.set_cookiejar(cj)
227
        br.set_handle_equiv(True)
228
        br.set_handle_redirect(True)
229
        br.set_handle_referer(True)
230
        br.set_handle_robots(False)
231
        br.set_debug_http(False)
232
        br.set_debug_redirects(False)
233
        br.set_debug_responses(False)
234
 
235
        br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
236
 
237
        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'),
238
                         ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'),
239
                         ('Accept-Encoding', 'gzip,deflate,sdch'),                  
240
                         ('Accept-Language', 'en-US,en;q=0.8'),                     
241
                         ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.3')]
242
        return br
243
 
244
def ungzipResponse(r,b):
245
    headers = r.info()
246
    if headers['Content-Encoding']=='gzip':
247
        import gzip
248
        print "********************"
249
        print "Deflating gzip response"
250
        print "********************"
251
        gz = gzip.GzipFile(fileobj=r, mode='rb')
252
        html = gz.read()
253
        gz.close()
254
        headers["Content-type"] = "text/html; charset=utf-8"
255
        r.set_data( html )
256
        b.set_response(r)
257
 
258
 
259
def login(url):
260
    br = getBrowserObject()
261
    br.open(url)
262
    response = br.open(url)
263
    ungzipResponse(response, br)
264
    #html = response.read()
265
    #print html
266
    br.select_form(name="signinWidget")
267
    br.form['username'] = "kshitij.sood@saholic.com"
268
    br.form['password'] = "pioneer"
269
    response = br.submit()
270
    print "********************"
271
    print "Attempting to Login"
272
    print "********************"
273
    #ungzipResponse(response, br)
274
    return br
275
 
276
 
277
 
278
if __name__ == "__main__":
279
    parser = optparse.OptionParser()
280
    parser.add_option("-l", "--logfile", dest="logfile",
281
                      type="string",
282
                      help="Log all output to LOG_FILE",
283
                      )
284
    parser.add_option("-i", "--pidfile", dest="pidfile",
285
                      type="string",
286
                      help="Write the PID to pidfile")
287
    (options, args) = parser.parse_args()
288
    daemon = CompetitorScraping(options.logfile, options.pidfile)
289
    if len(args) == 0:
290
        daemon.run()
291
    elif len(args) == 1:
292
        if 'start' == args[0]:
293
            daemon.start()
294
        elif 'stop' == args[0]:
295
            daemon.stop()
296
        elif 'restart' == args[0]:
297
            daemon.restart()
298
        else:
299
            print "Unknown command"
300
            sys.exit(2)
301
        sys.exit(0)
302
    else:
303
        print "usage: %s start|stop|restart" % sys.argv[0]
304
        sys.exit(2)