| 15869 |
kshitij.so |
1 |
import urllib2
|
|
|
2 |
from BeautifulSoup import BeautifulSoup
|
|
|
3 |
import pymongo
|
|
|
4 |
import re
|
|
|
5 |
from dtr.utils.utils import to_java_date
|
|
|
6 |
import optparse
|
|
|
7 |
from datetime import datetime
|
|
|
8 |
import smtplib
|
|
|
9 |
from email.mime.text import MIMEText
|
|
|
10 |
from email.mime.multipart import MIMEMultipart
|
| 15895 |
kshitij.so |
11 |
from dtr.utils import ShopCluesScraper
|
|
|
12 |
import traceback
|
| 15869 |
kshitij.so |
13 |
|
|
|
14 |
con = None
|
|
|
15 |
parser = optparse.OptionParser()
|
|
|
16 |
parser.add_option("-m", "--m", dest="mongoHost",
|
|
|
17 |
default="localhost",
|
|
|
18 |
type="string", help="The HOST where the mongo server is running",
|
|
|
19 |
metavar="mongo_host")
|
|
|
20 |
|
|
|
21 |
(options, args) = parser.parse_args()
|
|
|
22 |
|
|
|
23 |
|
|
|
24 |
exceptionList = []
|
|
|
25 |
bestSellers = []
|
|
|
26 |
baseUrl = "http://m.shopclues.com/products/getProductList/mobiles:top-selling-mobiles-and-tablets.html/%s/page=%s"
|
| 15895 |
kshitij.so |
27 |
headers = {
|
|
|
28 |
'User-Agent':'Mozilla/5.0 (Linux; Android 4.3; Nexus 7 Build/JSS15Q) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.72 Safari/537.36',
|
|
|
29 |
'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
|
|
|
30 |
'Accept-Language' : 'en-US,en;q=0.8',
|
|
|
31 |
'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
|
|
|
32 |
'Connection':'keep-alive',
|
|
|
33 |
'Accept-Encoding' : 'gzip,deflate,sdch'
|
|
|
34 |
}
|
| 15869 |
kshitij.so |
35 |
now = datetime.now()
|
| 15895 |
kshitij.so |
36 |
sc = ShopCluesScraper.ShopCluesScraper()
|
| 15869 |
kshitij.so |
37 |
|
|
|
38 |
|
|
|
39 |
class __ProductInfo:
|
|
|
40 |
|
|
|
41 |
def __init__(self, identifier, rank, url, available_price, in_stock, codAvailable, source_product_name, thumbnail, coupon):
|
|
|
42 |
self.identifier = identifier
|
|
|
43 |
self.rank = rank
|
|
|
44 |
self.url = url
|
|
|
45 |
self.available_price = available_price
|
|
|
46 |
self.in_stock = in_stock
|
|
|
47 |
self.codAvailable = codAvailable
|
|
|
48 |
self.source_product_name = source_product_name
|
|
|
49 |
self.thumbnail = thumbnail
|
|
|
50 |
self.coupon = coupon
|
|
|
51 |
|
|
|
52 |
def get_mongo_connection(host=options.mongoHost, port=27017):
|
|
|
53 |
global con
|
|
|
54 |
if con is None:
|
|
|
55 |
print "Establishing connection %s host and port %d" %(host,port)
|
|
|
56 |
try:
|
|
|
57 |
con = pymongo.MongoClient(host, port)
|
|
|
58 |
except Exception, e:
|
|
|
59 |
print e
|
|
|
60 |
return None
|
|
|
61 |
return con
|
|
|
62 |
|
|
|
63 |
def getSoupObject(url):
|
|
|
64 |
print "Getting soup object for"
|
|
|
65 |
print url
|
|
|
66 |
global RETRY_COUNT
|
|
|
67 |
RETRY_COUNT = 1
|
|
|
68 |
while RETRY_COUNT < 10:
|
|
|
69 |
try:
|
|
|
70 |
soup = None
|
| 15895 |
kshitij.so |
71 |
request = urllib2.Request(url, headers)
|
| 15869 |
kshitij.so |
72 |
response = urllib2.urlopen(request)
|
|
|
73 |
response_data = response.read()
|
|
|
74 |
response.close()
|
|
|
75 |
try:
|
|
|
76 |
page=response_data.decode("utf-8")
|
|
|
77 |
soup = BeautifulSoup(page,convertEntities=BeautifulSoup.HTML_ENTITIES)
|
|
|
78 |
except:
|
|
|
79 |
soup = BeautifulSoup(response_data,convertEntities=BeautifulSoup.HTML_ENTITIES)
|
|
|
80 |
if soup is None:
|
|
|
81 |
raise
|
|
|
82 |
return soup
|
|
|
83 |
except Exception as e:
|
|
|
84 |
print e
|
|
|
85 |
print "Retrying"
|
|
|
86 |
RETRY_COUNT = RETRY_COUNT + 1
|
|
|
87 |
|
|
|
88 |
|
|
|
89 |
def scrapeBestSellers():
|
|
|
90 |
global bestSellers
|
|
|
91 |
bestSellers = []
|
|
|
92 |
rank = 0
|
|
|
93 |
page = 1
|
|
|
94 |
while (True):
|
|
|
95 |
url = (baseUrl)%(page,page-1)
|
|
|
96 |
soup = getSoupObject(url)
|
|
|
97 |
productDivs = soup.findAll('div',{'class':'pd-list-cont'})
|
|
|
98 |
if productDivs is None or len(productDivs)==0:
|
|
|
99 |
return
|
|
|
100 |
for productDiv in productDivs:
|
|
|
101 |
rank = rank + 1
|
|
|
102 |
info_tag = productDiv.find('a')
|
|
|
103 |
link = info_tag['href']
|
|
|
104 |
scin = info_tag['data-id'].strip()
|
|
|
105 |
print link
|
|
|
106 |
print scin
|
| 15895 |
kshitij.so |
107 |
productName = productDiv.find('div',{'class':'pdt-name'}).string
|
|
|
108 |
try:
|
|
|
109 |
productInfo = sc.read(link)
|
|
|
110 |
except Exception as e:
|
|
|
111 |
traceback.print_exc()
|
|
|
112 |
continue
|
| 15869 |
kshitij.so |
113 |
product = list(get_mongo_connection().Catalog.MasterData.find({'source_id':5,'identifier':scin}))
|
|
|
114 |
if len(product) > 0:
|
| 15895 |
kshitij.so |
115 |
get_mongo_connection().Catalog.MasterData.update({'source_id':5,'identifier':scin},{"$set":{'rank':rank, 'available_price':productInfo['price'], \
|
|
|
116 |
'in_stock':productInfo['inStock'], 'codAvailable':productInfo['isCod'], \
|
|
|
117 |
'coupon':productInfo['coupon']}})
|
| 15869 |
kshitij.so |
118 |
else:
|
|
|
119 |
#Lets bundle product by finding similar url pattern
|
| 15895 |
kshitij.so |
120 |
uri = link.replace('http://m.shopclues.com','').replace(".html","")
|
|
|
121 |
try:
|
|
|
122 |
int(uri[uri.rfind('-')+1:])
|
|
|
123 |
uri = uri[:uri.rfind('-')]
|
|
|
124 |
except:
|
|
|
125 |
pass
|
|
|
126 |
product = list(get_mongo_connection().Catalog.MasterData.find({'source_id':5,'marketPlaceUrl':{'$regex': uri}}))
|
|
|
127 |
toBundle = __ProductInfo(scin, rank, link, productInfo['price'], productInfo['inStock'],productInfo['isCod'], productName, "" ,productInfo['coupon'])
|
| 15869 |
kshitij.so |
128 |
if len(product) > 0:
|
| 15895 |
kshitij.so |
129 |
bundleNewProduct(product[0], toBundle)
|
|
|
130 |
else:
|
|
|
131 |
exceptionList.append(toBundle)
|
| 15869 |
kshitij.so |
132 |
page = page+1
|
|
|
133 |
|
|
|
134 |
def bundleNewProduct(existingProduct, toBundle):
|
| 15895 |
kshitij.so |
135 |
print "Adding new product"
|
|
|
136 |
try:
|
|
|
137 |
max_id = list(get_mongo_connection().Catalog.MasterData.find().sort([('_id',pymongo.DESCENDING)]).limit(1))
|
|
|
138 |
existingProduct['_id'] = max_id[0]['_id'] + 1
|
|
|
139 |
existingProduct['addedOn'] = to_java_date(datetime.now())
|
|
|
140 |
existingProduct['available_price'] = toBundle.available_price
|
|
|
141 |
existingProduct['updatedOn'] = to_java_date(datetime.now())
|
|
|
142 |
existingProduct['codAvailable'] = toBundle.codAvailable
|
|
|
143 |
existingProduct['coupon'] = toBundle.coupon
|
|
|
144 |
existingProduct['identifier'] = toBundle.identifier
|
|
|
145 |
existingProduct['in_stock'] = toBundle.in_stock
|
|
|
146 |
existingProduct['marketPlaceUrl'] = toBundle.url
|
|
|
147 |
existingProduct['rank'] = toBundle.rank
|
|
|
148 |
existingProduct['source_product_name'] = toBundle.source_product_name
|
|
|
149 |
existingProduct['url'] = toBundle.url
|
|
|
150 |
get_mongo_connection().Catalog.MasterData.insert(existingProduct)
|
|
|
151 |
return {1:'Data added successfully.'}
|
|
|
152 |
except Exception as e:
|
|
|
153 |
print e
|
|
|
154 |
return {0:'Unable to add data.'}
|
| 15869 |
kshitij.so |
155 |
|
| 15895 |
kshitij.so |
156 |
def exceptionItems():
|
|
|
157 |
for item in exceptionList:
|
|
|
158 |
print vars(item)
|
|
|
159 |
|
|
|
160 |
|
| 15869 |
kshitij.so |
161 |
def main():
|
|
|
162 |
scrapeBestSellers()
|
| 15895 |
kshitij.so |
163 |
exceptionItems()
|
| 15869 |
kshitij.so |
164 |
|
|
|
165 |
if __name__=='__main__':
|
|
|
166 |
main()
|