Subversion Repositories SmartDukaan

Rev

Rev 14745 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
13831 kshitij.so 1
from BeautifulSoup import BeautifulSoup
2
import re
3
from sys import exit
14745 kshitij.so 4
from dtr.utils.utils import fetchResponseUsingProxy
13831 kshitij.so 5
 
14176 kshitij.so 6
headers = { 
7
           'User-agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11',
8
            'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',      
9
            'Accept-Language' : 'en-US,en;q=0.8',                     
10
            'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
11
            'Cookie':'T=TI141257426738726661427143281839817329423126740566618323641725716448; __sonar=7237334677420142002; __gads=ID=c8b82101a0e4f451:T=1412574724:S=ALNI_MbPMbEOZj2nAGjM54z8ZHFMqwTOTQ; FK-CMP-DATA=; SN=2.VI11FB3FB6ED9D4693A796AB8C965B3417.SI802C325AC43444858830E870C4FD3324.VS141257426735693951472.1412576209; VID=2.VI11FB3FB6ED9D4693A796AB8C965B3417.1412576209.VS141257426735693951472; NSID=2.SI802C325AC43444858830E870C4FD3324.1412576209.VI11FB3FB6ED9D4693A796AB8C965B3417; __utma=19769839.709301254.1412574234.1412574234.1412574234.1; __utmb=19769839.23.10.1412574234; __utmc=19769839; __utmz=19769839.1412574234.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); s_cc=true; gpv_pn=SellerListing%3AMobile%3AMicromax%20Canvas%20Fire%20A093; gpv_pn_t=no%20value; s_sq=%5B%5BB%5D%5D; s_ppv=36',
14745 kshitij.so 12
            'Host':'www.flipkart.com',
13
            'Accept-Encoding' : 'gzip,deflate,sdch'
14176 kshitij.so 14
        }
15
 
13831 kshitij.so 16
class FlipkartScraper:
17
    def __init__(self):
18
        self.count_trials = 0
19
        self.redirectCount = 0
20
 
21
    def read(self, url):
22
        try:
14745 kshitij.so 23
            """quick fix,need to add it conf""" 
24
 
25
            response_data = fetchResponseUsingProxy(url, headers)
26
 
13831 kshitij.so 27
        except Exception as e:
28
            print 'ERROR: ', e
29
            print 'Retrying'
30
            self.count_trials += 1
31
 
32
            if self.count_trials < 3:
33
                return self.read(url)
34
 
35
        self.response_data=response_data
14168 kshitij.so 36
        return self.createSoup(url)
13831 kshitij.so 37
 
14168 kshitij.so 38
#    def scrapeRedirectedPage(self,soup,redirect_url):
39
#        print soup
40
#        print redirect_url
41
#        t = soup.find("div" , {"class" : "seller-table fk-user-select-none line"})
42
#        print t
43
#        table_rows = t.findAll("tr" , {"class" : re.compile('t-row.*')})
44
#        print table_rows
45
#        for x in table_rows:
46
#            print x
47
#    
48
    def createSoup(self, url):
13831 kshitij.so 49
        print "Creating soup from flipkart data for %s" %(url)
50
        page=self.response_data.decode("utf-8")
51
        self.soup = BeautifulSoup(page,convertEntities=BeautifulSoup.HTML_ENTITIES)
52
        page = None
53
        self.response_data = None
54
        print "Soup created from flipkart data for %s" %(url)
14168 kshitij.so 55
        return self.scrape(self.soup,url)
13831 kshitij.so 56
 
57
    def scrape(self,soup,url):
58
        print "Inside json creator for %s" %(url)
59
        info = []
15265 kshitij.so 60
        buyBoxInfo = []
13831 kshitij.so 61
        oddSeller = soup.findAll("div" , {"class" : "line seller-item odd "})
62
        for data in oddSeller:
63
            temp={}
64
            price = data.find('span', attrs={'class' : re.compile('pxs-final-price.*')}).string.strip('Rs.').strip()
65
            temp['sellingPrice']=float(price)
66
            for metrics in data.find("div",{"class":"fk-text-right"}):
67
                try:
68
                    metric = metrics.findAll('input', {'type': 'submit'})
69
                except AttributeError:
70
                    continue
15265 kshitij.so 71
                try:
72
                    inputTags = metric[0]['data-lst-buytrend']
73
                except TypeError:
74
                    continue
13831 kshitij.so 75
                dataMetrics = metric[0]['data-listing-metrics']
76
                dataMetric = dataMetrics.split(';')
77
                temp['sellingPriceMetric'] = float(dataMetric[1])
13935 kshitij.so 78
                try:
79
                    temp['shippingFee'] = float(dataMetric[2])
80
                except:
81
                    temp['shippingFee'] = 0.0
15265 kshitij.so 82
                try:
83
                    buyTrend = inputTags[0:str(inputTags).index('NWSR')].replace('_','')
84
                except ValueError:
85
                    buyTrend = inputTags[0:str(inputTags).index('WSR')].replace('_','')
86
                temp['buyTrend']=buyTrend.strip()
87
                temp['sellingPrice'] = temp['sellingPrice'] + temp['shippingFee']
88
                if temp['buyTrend'] in  ('PrefNCheap','PrefCheap'):
89
                    buyBoxInfo.append(temp)
13831 kshitij.so 90
                info.append(temp)
91
        evenSeller = soup.findAll("div" , {"class" : "line seller-item even "})
92
        for data in evenSeller:
93
            temp={}
94
            price = data.find('span', attrs={'class' : re.compile('pxs-final-price.*')}).string.strip('Rs.')
95
            temp['sellingPrice']=float(price)
96
            for metrics in data.find("div",{"class":"fk-text-right"}):
97
                try:
98
                    metric = metrics.findAll('input', {'type': 'submit'})
99
                except AttributeError:
100
                    continue
15265 kshitij.so 101
                try:
102
                    inputTags = metric[0]['data-lst-buytrend']
103
                except TypeError:
104
                    continue
13831 kshitij.so 105
                dataMetrics = metric[0]['data-listing-metrics']
106
                dataMetric = dataMetrics.split(';')
107
                temp['sellingPriceMetric'] = float(dataMetric[1])
13935 kshitij.so 108
                try:
109
                    temp['shippingFee'] = float(dataMetric[2])
110
                except:
111
                    temp['shippingFee'] = 0.0
15265 kshitij.so 112
                try:
113
                    buyTrend = inputTags[0:str(inputTags).index('NWSR')].replace('_','')
114
                except ValueError:
115
                    buyTrend = inputTags[0:str(inputTags).index('WSR')].replace('_','')
116
                temp['buyTrend']=buyTrend.strip()
117
                temp['sellingPrice'] = temp['sellingPrice'] + temp['shippingFee']
118
                if temp['buyTrend'] in  ('PrefNCheap','PrefCheap'):
119
                    buyBoxInfo.append(temp)  
13831 kshitij.so 120
                info.append(temp)
121
        print info
15265 kshitij.so 122
        print "==========="
123
        print buyBoxInfo
13831 kshitij.so 124
        print "Returning Json response from flipkart for %s" %(url)
15265 kshitij.so 125
        return info, buyBoxInfo
13831 kshitij.so 126
 
127
if __name__ == '__main__':
128
    scraper = FlipkartScraper()
15265 kshitij.so 129
    x, z = scraper.read('http://www.flipkart.com/ps/MOBDUZSYZCA7HDYW')
130
    for y in x:
131
        print y
132
    print "==========="
133
    for t in z:
134
        print t