Subversion Repositories SmartDukaan

Rev

Rev 11193 | Rev 11668 | 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
4
 
5
class FlipkartScraper:
6
    def __init__(self):
7
        self.count_trials = 0
8
 
9
    def read(self, url):
10
        request = urllib2.Request(url)
11
        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')
12
        opener = urllib2.build_opener()
13
        response_data = ""
14
        try:
15
            response_data = opener.open(request).read()
16
 
17
        except urllib2.HTTPError as e:
18
            print 'ERROR: ', e
19
            print 'Retrying'
20
            self.count_trials += 1
21
 
22
            if self.count_trials < 3:
23
                return self.read(url)
24
 
25
        self.response_data=response_data
26
 
27
    def createData(self):
28
        page=self.response_data.decode("utf-8")
29
        self.soup = BeautifulSoup(page,convertEntities=BeautifulSoup.HTML_ENTITIES)
30
        return self.scrape(self.soup)
31
 
32
 
33
    def scrape(self,soup):
34
        info = []
35
        oddSeller = soup.findAll("div" , {"class" : "line seller-item odd "})
36
        for data in oddSeller:
37
            temp={}
38
            price = data.find('span', attrs={'class' : re.compile('pxs-final-price.*')}).string.strip('Rs.').strip()
39
            temp['sellingPrice']=float(price)
40
            for sellerInfo in data.findAll("div",{"class":re.compile(".*seller-info*")}):
41
                sellerName = sellerInfo.find('a').string
42
                temp['sellerName'] = sellerName
43
            for metrics in data.find("div",{"class":"fk-text-right"}):
44
                try:
11217 kshitij.so 45
                    metric = metrics.findAll('input', {'type': 'submit'})
46
                except AttributeError:
47
                    continue
48
                try:
49
                    inputTags = metric[0]['data-lst-buytrend']
10503 kshitij.so 50
                except TypeError:
51
                    continue
11217 kshitij.so 52
                dataMetrics = metric[0]['data-listing-metrics']
10503 kshitij.so 53
                try:
54
                    buyTrend = inputTags[0:str(inputTags).index('NWSR')].replace('_','')
55
                except ValueError:
56
                    buyTrend = inputTags[0:str(inputTags).index('WSR')].replace('_','')
57
                temp['buyTrend']=buyTrend
58
                dataMetric = dataMetrics.split(';')
59
                sellerCode = dataMetric[0]
60
                temp['sellerCode']=sellerCode
61
                temp['sellingPriceMetric'] = float(dataMetric[1])
62
                temp['shippingTime'] = dataMetric[3]
63
                temp['sellerScore'] = int(dataMetric[4])
64
                info.append(temp)
65
        evenSeller = soup.findAll("div" , {"class" : "line seller-item even "})
66
        for data in evenSeller:
67
            temp={}
68
            price = data.find('span', attrs={'class' : re.compile('pxs-final-price.*')}).string.strip('Rs.')
69
            temp['sellingPrice']=float(price)
70
            for sellerInfo in data.findAll("div",{"class":re.compile(".*seller-info*")}):
71
                sellerName = sellerInfo.find('a').string
72
                temp['sellerName'] = sellerName
73
            for metrics in data.find("div",{"class":"fk-text-right"}):
74
                try:
11217 kshitij.so 75
                    metric = metrics.findAll('input', {'type': 'submit'})
76
                except AttributeError:
77
                    continue
78
                try:
79
                    inputTags = metric[0]['data-lst-buytrend']
10503 kshitij.so 80
                except TypeError:
81
                    continue
11217 kshitij.so 82
                dataMetrics = metric[0]['data-listing-metrics']
10503 kshitij.so 83
                try:
84
                    buyTrend = inputTags[0:str(inputTags).index('NWSR')].replace('_','')
85
                except ValueError:
86
                    buyTrend = inputTags[0:str(inputTags).index('WSR')].replace('_','')
87
                temp['buyTrend']=buyTrend
88
                dataMetric = dataMetrics.split(';')
89
                temp['sellerCode'] = dataMetric[0] 
90
                temp['sellingPriceMetric'] = float(dataMetric[1])
91
                temp['shippingTime'] = dataMetric[3]
92
                temp['sellerScore'] = int(dataMetric[4])
93
                info.append(temp)
94
        return info
95
 
96
if __name__ == '__main__':
97
    scraper = FlipkartScraper()
11217 kshitij.so 98
    scraper.read('http://www.flipkart.com/ps/ACCCZJZNQYSRGH8F')
10503 kshitij.so 99
    print scraper.createData()
100