Subversion Repositories SmartDukaan

Rev

Rev 12206 | Rev 12212 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
10503 kshitij.so 1
import urllib2
2
from BeautifulSoup import BeautifulSoup
3
import re
11668 kshitij.so 4
from sys import exit
10503 kshitij.so 5
 
6
class FlipkartScraper:
7
    def __init__(self):
8
        self.count_trials = 0
9
 
10
    def read(self, url):
11
        request = urllib2.Request(url)
12
        request.add_header('User-Agent', 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.218 Safari/535.1')
13
        opener = urllib2.build_opener()
14
        response_data = ""
15
        try:
16
            response_data = opener.open(request).read()
12199 kshitij.so 17
            print "Fetched response from flipkart for %s" %(url)
10503 kshitij.so 18
 
19
        except urllib2.HTTPError as e:
20
            print 'ERROR: ', e
21
            print 'Retrying'
22
            self.count_trials += 1
23
 
24
            if self.count_trials < 3:
25
                return self.read(url)
26
 
27
        self.response_data=response_data
28
        page=self.response_data.decode("utf-8")
12207 kshitij.so 29
        soup = BeautifulSoup(page,convertEntities=BeautifulSoup.HTML_ENTITIES)
11967 kshitij.so 30
        page = None
31
        self.response_data = None
12200 kshitij.so 32
        print "Soup created from flipkart data for %s" %(url)
10503 kshitij.so 33
        info = []
34
        oddSeller = soup.findAll("div" , {"class" : "line seller-item odd "})
35
        for data in oddSeller:
36
            temp={}
11668 kshitij.so 37
            try:
38
                businessDays = data.find('span', attrs={'class' : re.compile('fk-deliverable.*')})
39
                shippingTime = businessDays.find('span', attrs={'class' : re.compile('fk-bold')}).string.replace('to','').replace('business days.','').strip().replace('  ','-')
40
                temp['shippingTime']=shippingTime
41
            except:
42
                pass
10503 kshitij.so 43
            price = data.find('span', attrs={'class' : re.compile('pxs-final-price.*')}).string.strip('Rs.').strip()
44
            temp['sellingPrice']=float(price)
45
            for sellerInfo in data.findAll("div",{"class":re.compile(".*seller-info*")}):
46
                sellerName = sellerInfo.find('a').string
47
                temp['sellerName'] = sellerName
48
            for metrics in data.find("div",{"class":"fk-text-right"}):
49
                try:
11217 kshitij.so 50
                    metric = metrics.findAll('input', {'type': 'submit'})
51
                except AttributeError:
52
                    continue
53
                try:
54
                    inputTags = metric[0]['data-lst-buytrend']
10503 kshitij.so 55
                except TypeError:
56
                    continue
11217 kshitij.so 57
                dataMetrics = metric[0]['data-listing-metrics']
10503 kshitij.so 58
                try:
59
                    buyTrend = inputTags[0:str(inputTags).index('NWSR')].replace('_','')
60
                except ValueError:
61
                    buyTrend = inputTags[0:str(inputTags).index('WSR')].replace('_','')
62
                temp['buyTrend']=buyTrend
63
                dataMetric = dataMetrics.split(';')
64
                sellerCode = dataMetric[0]
65
                temp['sellerCode']=sellerCode
66
                temp['sellingPriceMetric'] = float(dataMetric[1])
11668 kshitij.so 67
                if not temp.has_key('shippingTime'):
68
                    print "Populating shipping time from metrics"
69
                    temp['shippingTime'] = dataMetric[3]
10503 kshitij.so 70
                temp['sellerScore'] = int(dataMetric[4])
71
                info.append(temp)
72
        evenSeller = soup.findAll("div" , {"class" : "line seller-item even "})
73
        for data in evenSeller:
74
            temp={}
75
            price = data.find('span', attrs={'class' : re.compile('pxs-final-price.*')}).string.strip('Rs.')
11668 kshitij.so 76
            try:
77
                businessDays = data.find('span', attrs={'class' : re.compile('fk-deliverable.*')})
78
                shippingTime = businessDays.find('span', attrs={'class' : re.compile('fk-bold')}).string.replace('to','').replace('business days.','').strip().replace('  ','-')
79
                temp['shippingTime']=shippingTime
80
            except:
81
                pass
10503 kshitij.so 82
            temp['sellingPrice']=float(price)
83
            for sellerInfo in data.findAll("div",{"class":re.compile(".*seller-info*")}):
84
                sellerName = sellerInfo.find('a').string
85
                temp['sellerName'] = sellerName
86
            for metrics in data.find("div",{"class":"fk-text-right"}):
87
                try:
11217 kshitij.so 88
                    metric = metrics.findAll('input', {'type': 'submit'})
89
                except AttributeError:
90
                    continue
91
                try:
92
                    inputTags = metric[0]['data-lst-buytrend']
10503 kshitij.so 93
                except TypeError:
94
                    continue
11217 kshitij.so 95
                dataMetrics = metric[0]['data-listing-metrics']
10503 kshitij.so 96
                try:
97
                    buyTrend = inputTags[0:str(inputTags).index('NWSR')].replace('_','')
98
                except ValueError:
99
                    buyTrend = inputTags[0:str(inputTags).index('WSR')].replace('_','')
100
                temp['buyTrend']=buyTrend
101
                dataMetric = dataMetrics.split(';')
102
                temp['sellerCode'] = dataMetric[0] 
103
                temp['sellingPriceMetric'] = float(dataMetric[1])
11668 kshitij.so 104
                if not temp.has_key('shippingTime'):
105
                    print "Populating shipping time from metrics"
106
                    temp['shippingTime'] = dataMetric[3]
10503 kshitij.so 107
                temp['sellerScore'] = int(dataMetric[4])
108
                info.append(temp)
12200 kshitij.so 109
        print "Returning Json response from flipkart for %s" %(url)
10503 kshitij.so 110
        return info
111
 
112
if __name__ == '__main__':
113
    scraper = FlipkartScraper()
12202 kshitij.so 114
    print scraper.read('http://www.flipkart.com/ps/ACCDSN84XXH5P9WG')
10503 kshitij.so 115