Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
15519 kshitij.so 1
from BeautifulSoup import BeautifulSoup
2
import urllib2
3
from sys import exit
4
import json
5
import re
6
import traceback
7
from dtr.utils.utils import ungzipResponse
8
 
9
 
10
headers = { 
11
            'User-agent':'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36',
12
            'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',      
13
            'Accept-Language' : 'en-US,en;q=0.8',                     
14
            'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
15
            '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; pincode=110011; s_ppv=36',
16
            'Connection':'keep-alive',
17
            'Accept-Encoding' : 'gzip,deflate,sdch'
18
        }
19
 
20
searchUrl = "http://www.flipkart.com/search?q="
21
 
22
class FlipkartProductPageScraper:
23
    def __init__(self):
24
        self.count_trials = 0
25
        self.redirectCount = 0
26
 
27
    def read(self, pid):
28
        response_data = ""
29
        redirect_url = ""
30
        try:
31
 
32
            """quick fix,need to add it conf""" 
33
            url = searchUrl+pid
34
            print url
35
            req = urllib2.Request(url,headers=headers)
36
            response = urllib2.urlopen(req)
37
            response_data = ungzipResponse(response)
38
            print "Fetched response from flipkart for %s" %(url)
39
            #redirect_url = response.url
40
 
41
        except Exception as e:
42
            traceback.print_exc()
43
            print 'ERROR: ', e
44
            print 'Retrying'
45
            self.count_trials += 1
46
 
47
            if self.count_trials < 3:
48
                return self.read(url)
49
 
50
        self.response_data=response_data
51
        return self.createData(url,redirect_url)
52
 
53
    def scrapeRedirectedPage(self,soup,redirect_url):
54
        print soup
55
        print redirect_url
56
        t = soup.find("div" , {"class" : "seller-table fk-user-select-none line"})
57
        print t
58
        table_rows = t.findAll("tr" , {"class" : re.compile('t-row.*')})
59
        print table_rows
60
        for x in table_rows:
61
            print x
62
 
63
    def createData(self,url, redirect_url):
64
        print "Creating soup from flipkart data for %s" %(url)
65
        #redirect_url = redirect_url.replace('www.flipkart.com','163.53.77.21')
66
        print "Redirect url is %s"%(redirect_url)
67
        page=self.response_data.decode("utf-8")
68
        self.soup = BeautifulSoup(page,convertEntities=BeautifulSoup.HTML_ENTITIES)
69
        page = None
70
        self.response_data = None
71
        print "Soup created from flipkart data for %s" %(url)
72
        print redirect_url
73
        return self.scrape(self.soup)
74
 
75
    def scrape(self,soup):
76
        saholicPrice = 0.0
77
        cheapestSeller = ''
78
        sellingPrice = 0.0
79
        try:
80
            print "data-config"
81
            if soup.find('div',{'class':'seller-table-wrap section'}) is None:
82
                raise
83
            sellerData = json.loads(soup.find('div',{'class':'seller-table-wrap section'})['data-config'])['dataModel']
84
            for seller in sellerData:
85
                if (seller['sellerInfo'].get('name')).strip() == 'Saholic':
86
                    saholicPrice = float(seller['priceInfo'].get('sellingPrice')) 
87
            lines = sorted(sellerData, key=lambda k: k['priceInfo'].get('sellingPrice', 0), reverse=False)
88
            sellingPrice =  float(lines[0]['priceInfo']['sellingPrice'])
89
            cheapestSeller = (lines[0]['sellerInfo'].get('name')).strip()
90
        except:
91
            """No able to parse seller wrap section, probably due to only single seller option"""
92
            buyBoxPrice = float(soup.find('span',{'class':'selling-price omniture-field'})['data-evar48'])
93
            sellerDiv = soup.find('div',{'class':'seller-badge omniture-field'})
94
            cheapestSeller =  (sellerDiv.find('a',{'class':'seller-name'}).string)
95
            sellingPrice = buyBoxPrice
96
            if soup.find('div',{'class':'out-of-stock'}) is not None:
97
                inStock = 0
98
            else:
99
                inStock = 1
100
        return {'cheapestSeller':cheapestSeller,'lowestSellingPrice':sellingPrice,'saholicSellingPrice':saholicPrice}
101
 
102
if __name__ == '__main__':
103
    scraper = FlipkartProductPageScraper()
104
    print scraper.read('MOBDUZSYZCA7HDYW')