Subversion Repositories SmartDukaan

Rev

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