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