Subversion Repositories SmartDukaan

Rev

Rev 13831 | Rev 14157 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
13831 kshitij.so 1
import urllib2
2
from BeautifulSoup import BeautifulSoup
3
import re
4
from sys import exit
5
 
6
class FlipkartScraper:
7
    def __init__(self):
8
        self.count_trials = 0
9
        self.redirectCount = 0
10
 
11
    def read(self, url):
12
        #url = url.replace('www.flipkart.com','163.53.77.21')
13
        url = url.replace('www.flipkart.com','163.53.76.55')
14
        print url
15
        request = urllib2.Request(url)
16
        request.add_header('Accept','text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
17
        #request.add_header('Accept-Charset','ISO-8859-1,utf-8;q=0.7,*;q=0.3')
18
        #request.add_header('Accept-Encoding','gzip,deflate,sdch')
19
        request.add_header('Accept-Language','en-US,en;q=0.8,hi;q=0.6')
20
        request.add_header('Connection','keep-alive')
21
        request.add_header('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')
22
        request.add_header('Cache-Control','max-age=0')
23
        request.add_header('Host','www.flipkart.com')
24
        request.add_header('User-Agent','Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36')
25
        response_data = ""
26
        redirect_url = ""
27
        try:
28
            response = urllib2.urlopen(request)
29
            response_data = response.read()
30
            print "Fetched response from flipkart for %s" %(url)
31
            redirect_url = response.url
32
 
33
        except Exception as e:
34
            print 'ERROR: ', e
35
            print 'Retrying'
36
            self.count_trials += 1
37
 
38
            if self.count_trials < 3:
39
                return self.read(url)
40
 
41
        self.response_data=response_data
42
        return self.createData(url,redirect_url)
43
 
44
    def scrapeRedirectedPage(self,soup,redirect_url):
45
        print soup
46
        print redirect_url
47
        t = soup.find("div" , {"class" : "seller-table fk-user-select-none line"})
48
        print t
49
        table_rows = t.findAll("tr" , {"class" : re.compile('t-row.*')})
50
        print table_rows
51
        for x in table_rows:
52
            print x
53
 
54
    def createData(self,url, redirect_url):
55
        print "Creating soup from flipkart data for %s" %(url)
56
        #redirect_url = redirect_url.replace('www.flipkart.com','163.53.77.21')
57
        print "Redirect url is %s"%(redirect_url)
58
        page=self.response_data.decode("utf-8")
59
        self.soup = BeautifulSoup(page,convertEntities=BeautifulSoup.HTML_ENTITIES)
60
        page = None
61
        self.response_data = None
62
        print "Soup created from flipkart data for %s" %(url)
63
        if (url==redirect_url):
64
            return self.scrape(self.soup,url)
65
        else:
66
            print self.redirectCount
67
            self.redirectCount+=1
68
            if self.redirectCount >5:
69
                raise
70
            return self.read(url)
71
 
72
 
73
 
74
 
75
    def scrape(self,soup,url):
76
        print "Inside json creator for %s" %(url)
77
        info = []
78
        oddSeller = soup.findAll("div" , {"class" : "line seller-item odd "})
79
        for data in oddSeller:
80
            temp={}
81
            try:
82
                businessDays = data.find('span', attrs={'class' : re.compile('fk-deliverable.*')})
83
                shippingTime = businessDays.find('span', attrs={'class' : re.compile('fk-bold')}).string.replace('to','').replace('business days.','').strip().replace('  ','-')
84
                temp['shippingTime']=shippingTime
85
            except:
86
                pass
87
            price = data.find('span', attrs={'class' : re.compile('pxs-final-price.*')}).string.strip('Rs.').strip()
88
            temp['sellingPrice']=float(price)
89
            for sellerInfo in data.findAll("div",{"class":re.compile(".*seller-info*")}):
90
                sellerName = sellerInfo.find('a').string
91
                temp['sellerName'] = sellerName
92
            for metrics in data.find("div",{"class":"fk-text-right"}):
93
                try:
94
                    metric = metrics.findAll('input', {'type': 'submit'})
95
                except AttributeError:
96
                    continue
97
                try:
98
                    inputTags = metric[0]['data-lst-buytrend']
99
                except TypeError:
100
                    continue
101
                dataMetrics = metric[0]['data-listing-metrics']
102
                try:
103
                    buyTrend = inputTags[0:str(inputTags).index('NWSR')].replace('_','')
104
                except ValueError:
105
                    buyTrend = inputTags[0:str(inputTags).index('WSR')].replace('_','')
106
                temp['buyTrend']=buyTrend
107
                dataMetric = dataMetrics.split(';')
108
                sellerCode = dataMetric[0]
109
                temp['sellerCode']=sellerCode
110
                temp['sellingPriceMetric'] = float(dataMetric[1])
111
                if not temp.has_key('shippingTime'):
112
                    print "Populating shipping time from metrics"
113
                    temp['shippingTime'] = dataMetric[3]
114
                temp['sellerScore'] = int(dataMetric[4])
13935 kshitij.so 115
                try:
116
                    temp['shippingFee'] = float(dataMetric[2])
117
                except:
118
                    temp['shippingFee'] = 0.0
119
                temp['sellingPrice'] = temp['sellingPrice'] + temp['shippingFee']  
13831 kshitij.so 120
                info.append(temp)
121
        evenSeller = soup.findAll("div" , {"class" : "line seller-item even "})
122
        for data in evenSeller:
123
            temp={}
124
            price = data.find('span', attrs={'class' : re.compile('pxs-final-price.*')}).string.strip('Rs.')
125
            try:
126
                businessDays = data.find('span', attrs={'class' : re.compile('fk-deliverable.*')})
127
                shippingTime = businessDays.find('span', attrs={'class' : re.compile('fk-bold')}).string.replace('to','').replace('business days.','').strip().replace('  ','-')
128
                temp['shippingTime']=shippingTime
129
            except:
130
                pass
131
            temp['sellingPrice']=float(price)
132
            for sellerInfo in data.findAll("div",{"class":re.compile(".*seller-info*")}):
133
                sellerName = sellerInfo.find('a').string
134
                temp['sellerName'] = sellerName
135
            for metrics in data.find("div",{"class":"fk-text-right"}):
136
                try:
137
                    metric = metrics.findAll('input', {'type': 'submit'})
138
                except AttributeError:
139
                    continue
140
                try:
141
                    inputTags = metric[0]['data-lst-buytrend']
142
                except TypeError:
143
                    continue
144
                dataMetrics = metric[0]['data-listing-metrics']
145
                try:
146
                    buyTrend = inputTags[0:str(inputTags).index('NWSR')].replace('_','')
147
                except ValueError:
148
                    buyTrend = inputTags[0:str(inputTags).index('WSR')].replace('_','')
149
                temp['buyTrend']=buyTrend
150
                dataMetric = dataMetrics.split(';')
151
                temp['sellerCode'] = dataMetric[0] 
152
                temp['sellingPriceMetric'] = float(dataMetric[1])
153
                if not temp.has_key('shippingTime'):
154
                    print "Populating shipping time from metrics"
155
                    temp['shippingTime'] = dataMetric[3]
156
                temp['sellerScore'] = int(dataMetric[4])
13935 kshitij.so 157
                try:
158
                    temp['shippingFee'] = float(dataMetric[2])
159
                except:
160
                    temp['shippingFee'] = 0.0
161
                temp['sellingPrice'] = temp['sellingPrice'] + temp['shippingFee']  
13831 kshitij.so 162
                info.append(temp)
163
        print info
164
        print "Returning Json response from flipkart for %s" %(url)
165
        return info
166
 
167
if __name__ == '__main__':
168
    scraper = FlipkartScraper()
169
    scraper.read('http://www.flipkart.com/ps/MOBDZB3Q8WJNKVHG')