Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
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
11
 
12
con = None
13
parser = optparse.OptionParser()
14
parser.add_option("-m", "--m", dest="mongoHost",
15
                      default="localhost",
16
                      type="string", help="The HOST where the mongo server is running",
17
                      metavar="mongo_host")
18
 
19
(options, args) = parser.parse_args()
20
 
21
 
22
exceptionList = []
23
bestSellers = []
24
baseUrl = "http://m.shopclues.com/products/getProductList/mobiles:top-selling-mobiles-and-tablets.html/%s/page=%s"
25
now = datetime.now()
26
 
27
 
28
class __ProductInfo:
29
 
30
    def __init__(self, identifier, rank, url, available_price, in_stock, codAvailable, source_product_name, thumbnail, coupon):
31
        self.identifier = identifier
32
        self.rank  = rank
33
        self.url = url
34
        self.available_price = available_price
35
        self.in_stock = in_stock
36
        self.codAvailable = codAvailable
37
        self.source_product_name = source_product_name
38
        self.thumbnail = thumbnail
39
        self.coupon = coupon 
40
 
41
def get_mongo_connection(host=options.mongoHost, port=27017):
42
    global con
43
    if con is None:
44
        print "Establishing connection %s host and port %d" %(host,port)
45
        try:
46
            con = pymongo.MongoClient(host, port)
47
        except Exception, e:
48
            print e
49
            return None
50
    return con
51
 
52
def getSoupObject(url):
53
    print "Getting soup object for"
54
    print url
55
    global RETRY_COUNT
56
    RETRY_COUNT = 1 
57
    while RETRY_COUNT < 10:
58
        try:
59
            soup = None
60
            request = urllib2.Request(url)
61
            request.add_header('Accept','text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
62
            request.add_header('Accept-Language','en-US,en;q=0.8,hi;q=0.6')
63
            request.add_header('Connection','keep-alive')
64
            request.add_header('User-Agent','Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36')
65
 
66
            response = urllib2.urlopen(request)   
67
            response_data = response.read()
68
            response.close()
69
            try:
70
                page=response_data.decode("utf-8")
71
                soup = BeautifulSoup(page,convertEntities=BeautifulSoup.HTML_ENTITIES)
72
            except:
73
                soup = BeautifulSoup(response_data,convertEntities=BeautifulSoup.HTML_ENTITIES)
74
            if soup is None:
75
                raise
76
            return soup
77
        except Exception as e:
78
            print e
79
            print "Retrying"
80
            RETRY_COUNT = RETRY_COUNT + 1
81
 
82
 
83
def scrapeBestSellers():
84
    global bestSellers
85
    bestSellers = []
86
    rank = 0
87
    page = 1
88
    while (True):
89
        url = (baseUrl)%(page,page-1)
90
        soup = getSoupObject(url)
91
        productDivs = soup.findAll('div',{'class':'pd-list-cont'})
92
        if productDivs is None or len(productDivs)==0:
93
            return
94
        for productDiv in productDivs:
95
            rank = rank + 1
96
            info_tag =  productDiv.find('a')
97
            link = info_tag['href']
98
            scin = info_tag['data-id'].strip()
99
            print link
100
            print scin
101
            product = list(get_mongo_connection().Catalog.MasterData.find({'source_id':5,'identifier':scin}))
102
            if len(product) > 0:
103
                get_mongo_connection().Catalog.MasterData.update({'source_id':5,'identifier':scin},{"$set":{'rank':rank}})
104
            else:
105
                #Lets bundle product by finding similar url pattern
106
                uri = link.replace('http://m.shopclues.com','')
107
                product = list(get_mongo_connection().Catalog.MasterData.find({'marketPlaceUrl':{'$regex': uri}}))
108
                if len(product) > 0:
109
                    bundleNewProduct(product[0],)
110
        page = page+1
111
 
112
def bundleNewProduct(existingProduct, toBundle):
113
    pass        
114
 
115
def main():
116
    scrapeBestSellers()
117
 
118
if __name__=='__main__':
119
    main()