Subversion Repositories SmartDukaan

Rev

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