Subversion Repositories SmartDukaan

Rev

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