Subversion Repositories SmartDukaan

Rev

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