Subversion Repositories SmartDukaan

Rev

Rev 11193 | Rev 11967 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

import urllib2
from BeautifulSoup import BeautifulSoup
import re

class FlipkartScraper:
    def __init__(self):
        self.count_trials = 0
    
    def read(self, url):
        request = urllib2.Request(url)
        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')
        opener = urllib2.build_opener()
        response_data = ""
        try:
            response_data = opener.open(request).read()
            
        except urllib2.HTTPError as e:
            print 'ERROR: ', e
            print 'Retrying'
            self.count_trials += 1
            
            if self.count_trials < 3:
                return self.read(url)
        
        self.response_data=response_data
    
    def createData(self):
        page=self.response_data.decode("utf-8")
        self.soup = BeautifulSoup(page,convertEntities=BeautifulSoup.HTML_ENTITIES)
        return self.scrape(self.soup)
    
    
    def scrape(self,soup):
        info = []
        oddSeller = soup.findAll("div" , {"class" : "line seller-item odd "})
        for data in oddSeller:
            temp={}
            price = data.find('span', attrs={'class' : re.compile('pxs-final-price.*')}).string.strip('Rs.').strip()
            temp['sellingPrice']=float(price)
            for sellerInfo in data.findAll("div",{"class":re.compile(".*seller-info*")}):
                sellerName = sellerInfo.find('a').string
                temp['sellerName'] = sellerName
            for metrics in data.find("div",{"class":"fk-text-right"}):
                try:
                    metric = metrics.findAll('input', {'type': 'submit'})
                except AttributeError:
                    continue
                try:
                    inputTags = metric[0]['data-lst-buytrend']
                except TypeError:
                    continue
                dataMetrics = metric[0]['data-listing-metrics']
                try:
                    buyTrend = inputTags[0:str(inputTags).index('NWSR')].replace('_','')
                except ValueError:
                    buyTrend = inputTags[0:str(inputTags).index('WSR')].replace('_','')
                temp['buyTrend']=buyTrend
                dataMetric = dataMetrics.split(';')
                sellerCode = dataMetric[0]
                temp['sellerCode']=sellerCode
                temp['sellingPriceMetric'] = float(dataMetric[1])
                temp['shippingTime'] = dataMetric[3]
                temp['sellerScore'] = int(dataMetric[4])
                info.append(temp)
        evenSeller = soup.findAll("div" , {"class" : "line seller-item even "})
        for data in evenSeller:
            temp={}
            price = data.find('span', attrs={'class' : re.compile('pxs-final-price.*')}).string.strip('Rs.')
            temp['sellingPrice']=float(price)
            for sellerInfo in data.findAll("div",{"class":re.compile(".*seller-info*")}):
                sellerName = sellerInfo.find('a').string
                temp['sellerName'] = sellerName
            for metrics in data.find("div",{"class":"fk-text-right"}):
                try:
                    metric = metrics.findAll('input', {'type': 'submit'})
                except AttributeError:
                    continue
                try:
                    inputTags = metric[0]['data-lst-buytrend']
                except TypeError:
                    continue
                dataMetrics = metric[0]['data-listing-metrics']
                try:
                    buyTrend = inputTags[0:str(inputTags).index('NWSR')].replace('_','')
                except ValueError:
                    buyTrend = inputTags[0:str(inputTags).index('WSR')].replace('_','')
                temp['buyTrend']=buyTrend
                dataMetric = dataMetrics.split(';')
                temp['sellerCode'] = dataMetric[0] 
                temp['sellingPriceMetric'] = float(dataMetric[1])
                temp['shippingTime'] = dataMetric[3]
                temp['sellerScore'] = int(dataMetric[4])
                info.append(temp)
        return info

if __name__ == '__main__':
    scraper = FlipkartScraper()
    scraper.read('http://www.flipkart.com/ps/ACCCZJZNQYSRGH8F')
    print scraper.createData()