Subversion Repositories SmartDukaan

Rev

Rev 12268 | Go to most recent revision | Details | Last modification | View Log | RSS feed

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