Subversion Repositories SmartDukaan

Rev

Rev 12207 | Rev 12215 | 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
12212 kshitij.so 28
        return self.createData(url)
29
 
30
    def createData(self,url):
10503 kshitij.so 31
        page=self.response_data.decode("utf-8")
12212 kshitij.so 32
        self.soup = BeautifulSoup(page,convertEntities=BeautifulSoup.HTML_ENTITIES)
11967 kshitij.so 33
        page = None
34
        self.response_data = None
12200 kshitij.so 35
        print "Soup created from flipkart data for %s" %(url)
12212 kshitij.so 36
        return self.scrape(self.soup,url)
37
 
38
 
39
    def scrape(self,soup,url):
10503 kshitij.so 40
        info = []
41
        oddSeller = soup.findAll("div" , {"class" : "line seller-item odd "})
42
        for data in oddSeller:
43
            temp={}
11668 kshitij.so 44
            try:
45
                businessDays = data.find('span', attrs={'class' : re.compile('fk-deliverable.*')})
46
                shippingTime = businessDays.find('span', attrs={'class' : re.compile('fk-bold')}).string.replace('to','').replace('business days.','').strip().replace('  ','-')
47
                temp['shippingTime']=shippingTime
48
            except:
49
                pass
10503 kshitij.so 50
            price = data.find('span', attrs={'class' : re.compile('pxs-final-price.*')}).string.strip('Rs.').strip()
51
            temp['sellingPrice']=float(price)
52
            for sellerInfo in data.findAll("div",{"class":re.compile(".*seller-info*")}):
53
                sellerName = sellerInfo.find('a').string
54
                temp['sellerName'] = sellerName
55
            for metrics in data.find("div",{"class":"fk-text-right"}):
56
                try:
11217 kshitij.so 57
                    metric = metrics.findAll('input', {'type': 'submit'})
58
                except AttributeError:
59
                    continue
60
                try:
61
                    inputTags = metric[0]['data-lst-buytrend']
10503 kshitij.so 62
                except TypeError:
63
                    continue
11217 kshitij.so 64
                dataMetrics = metric[0]['data-listing-metrics']
10503 kshitij.so 65
                try:
66
                    buyTrend = inputTags[0:str(inputTags).index('NWSR')].replace('_','')
67
                except ValueError:
68
                    buyTrend = inputTags[0:str(inputTags).index('WSR')].replace('_','')
69
                temp['buyTrend']=buyTrend
70
                dataMetric = dataMetrics.split(';')
71
                sellerCode = dataMetric[0]
72
                temp['sellerCode']=sellerCode
73
                temp['sellingPriceMetric'] = float(dataMetric[1])
11668 kshitij.so 74
                if not temp.has_key('shippingTime'):
75
                    print "Populating shipping time from metrics"
76
                    temp['shippingTime'] = dataMetric[3]
10503 kshitij.so 77
                temp['sellerScore'] = int(dataMetric[4])
78
                info.append(temp)
79
        evenSeller = soup.findAll("div" , {"class" : "line seller-item even "})
80
        for data in evenSeller:
81
            temp={}
82
            price = data.find('span', attrs={'class' : re.compile('pxs-final-price.*')}).string.strip('Rs.')
11668 kshitij.so 83
            try:
84
                businessDays = data.find('span', attrs={'class' : re.compile('fk-deliverable.*')})
85
                shippingTime = businessDays.find('span', attrs={'class' : re.compile('fk-bold')}).string.replace('to','').replace('business days.','').strip().replace('  ','-')
86
                temp['shippingTime']=shippingTime
87
            except:
88
                pass
10503 kshitij.so 89
            temp['sellingPrice']=float(price)
90
            for sellerInfo in data.findAll("div",{"class":re.compile(".*seller-info*")}):
91
                sellerName = sellerInfo.find('a').string
92
                temp['sellerName'] = sellerName
93
            for metrics in data.find("div",{"class":"fk-text-right"}):
94
                try:
11217 kshitij.so 95
                    metric = metrics.findAll('input', {'type': 'submit'})
96
                except AttributeError:
97
                    continue
98
                try:
99
                    inputTags = metric[0]['data-lst-buytrend']
10503 kshitij.so 100
                except TypeError:
101
                    continue
11217 kshitij.so 102
                dataMetrics = metric[0]['data-listing-metrics']
10503 kshitij.so 103
                try:
104
                    buyTrend = inputTags[0:str(inputTags).index('NWSR')].replace('_','')
105
                except ValueError:
106
                    buyTrend = inputTags[0:str(inputTags).index('WSR')].replace('_','')
107
                temp['buyTrend']=buyTrend
108
                dataMetric = dataMetrics.split(';')
109
                temp['sellerCode'] = dataMetric[0] 
110
                temp['sellingPriceMetric'] = float(dataMetric[1])
11668 kshitij.so 111
                if not temp.has_key('shippingTime'):
112
                    print "Populating shipping time from metrics"
113
                    temp['shippingTime'] = dataMetric[3]
10503 kshitij.so 114
                temp['sellerScore'] = int(dataMetric[4])
115
                info.append(temp)
12200 kshitij.so 116
        print "Returning Json response from flipkart for %s" %(url)
10503 kshitij.so 117
        return info
118
 
119
if __name__ == '__main__':
120
    scraper = FlipkartScraper()
12202 kshitij.so 121
    print scraper.read('http://www.flipkart.com/ps/ACCDSN84XXH5P9WG')
10503 kshitij.so 122