Subversion Repositories SmartDukaan

Rev

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