Subversion Repositories SmartDukaan

Rev

Rev 14176 | Rev 14542 | 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
 
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',
12
            'Host':'www.flipkart.com'
13
        }
14
 
13831 kshitij.so 15
class FlipkartScraper:
16
    def __init__(self):
17
        self.count_trials = 0
18
        self.redirectCount = 0
19
 
20
    def read(self, url):
21
        try:
14541 kshitij.so 22
            proxy = urllib2.ProxyHandler({'http': 'http://192.161.163.60:8800'})
23
            opener = urllib2.build_opener(proxy)
24
            urllib2.install_opener(opener)
25
            response = urllib2.urlopen(url)
13831 kshitij.so 26
            response_data = response.read()
14541 kshitij.so 27
            print response_data
14157 kshitij.so 28
            response.close()
14541 kshitij.so 29
#        try:
30
#            response = urllib2.urlopen(request)
31
#            response_data = response.read()
32
#            response.close()
33
#            print "Fetched response from flipkart for %s" %(url)
13831 kshitij.so 34
 
35
        except Exception as e:
36
            print 'ERROR: ', e
37
            print 'Retrying'
38
            self.count_trials += 1
39
 
40
            if self.count_trials < 3:
41
                return self.read(url)
42
 
43
        self.response_data=response_data
14168 kshitij.so 44
        return self.createSoup(url)
13831 kshitij.so 45
 
14168 kshitij.so 46
#    def scrapeRedirectedPage(self,soup,redirect_url):
47
#        print soup
48
#        print redirect_url
49
#        t = soup.find("div" , {"class" : "seller-table fk-user-select-none line"})
50
#        print t
51
#        table_rows = t.findAll("tr" , {"class" : re.compile('t-row.*')})
52
#        print table_rows
53
#        for x in table_rows:
54
#            print x
55
#    
56
    def createSoup(self, url):
13831 kshitij.so 57
        print "Creating soup from flipkart data for %s" %(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)
14168 kshitij.so 63
        return self.scrape(self.soup,url)
13831 kshitij.so 64
 
65
    def scrape(self,soup,url):
66
        print "Inside json creator for %s" %(url)
67
        info = []
68
        oddSeller = soup.findAll("div" , {"class" : "line seller-item odd "})
69
        for data in oddSeller:
70
            temp={}
71
            price = data.find('span', attrs={'class' : re.compile('pxs-final-price.*')}).string.strip('Rs.').strip()
72
            temp['sellingPrice']=float(price)
73
            for metrics in data.find("div",{"class":"fk-text-right"}):
74
                try:
75
                    metric = metrics.findAll('input', {'type': 'submit'})
76
                except AttributeError:
77
                    continue
78
                dataMetrics = metric[0]['data-listing-metrics']
79
                dataMetric = dataMetrics.split(';')
80
                temp['sellingPriceMetric'] = float(dataMetric[1])
13935 kshitij.so 81
                try:
82
                    temp['shippingFee'] = float(dataMetric[2])
83
                except:
84
                    temp['shippingFee'] = 0.0
85
                temp['sellingPrice'] = temp['sellingPrice'] + temp['shippingFee']  
13831 kshitij.so 86
                info.append(temp)
87
        evenSeller = soup.findAll("div" , {"class" : "line seller-item even "})
88
        for data in evenSeller:
89
            temp={}
90
            price = data.find('span', attrs={'class' : re.compile('pxs-final-price.*')}).string.strip('Rs.')
91
            temp['sellingPrice']=float(price)
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
                dataMetrics = metric[0]['data-listing-metrics']
98
                dataMetric = dataMetrics.split(';')
99
                temp['sellingPriceMetric'] = float(dataMetric[1])
13935 kshitij.so 100
                try:
101
                    temp['shippingFee'] = float(dataMetric[2])
102
                except:
103
                    temp['shippingFee'] = 0.0
104
                temp['sellingPrice'] = temp['sellingPrice'] + temp['shippingFee']  
13831 kshitij.so 105
                info.append(temp)
106
        print info
107
        print "Returning Json response from flipkart for %s" %(url)
108
        return info
109
 
110
if __name__ == '__main__':
111
    scraper = FlipkartScraper()
112
    scraper.read('http://www.flipkart.com/ps/MOBDZB3Q8WJNKVHG')