Subversion Repositories SmartDukaan

Rev

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