Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
14122 kshitij.so 1
import urllib2
2
from BeautifulSoup import BeautifulSoup
3
import re
4
from sys import exit
5
import json
6
 
7
headers = { 
8
            'User-agent':'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36',
9
            'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',      
10
            'Accept-Language' : 'en-US,en;q=0.8',                     
11
            'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
12
            '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',
13
            'Connection':'keep-alive'
14
        }
15
 
16
class FlipkartProductPageScraper:
17
    def __init__(self):
18
        self.count_trials = 0
19
        self.redirectCount = 0
20
 
21
    def read(self, url):
22
        response_data = ""
23
        redirect_url = ""
24
        try:
25
            req = urllib2.Request(url,headers=headers)
26
            response = urllib2.urlopen(req)
27
            response_data = response.read()
14366 kshitij.so 28
            response.close()
14122 kshitij.so 29
            print "Fetched response from flipkart for %s" %(url)
30
            redirect_url = response.url
31
 
32
        except Exception as e:
33
            print 'ERROR: ', e
34
            print 'Retrying'
35
            self.count_trials += 1
36
 
37
            if self.count_trials < 3:
38
                return self.read(url)
39
 
40
        self.response_data=response_data
41
        return self.createData(url,redirect_url)
42
 
43
    def scrapeRedirectedPage(self,soup,redirect_url):
44
        print soup
45
        print redirect_url
46
        t = soup.find("div" , {"class" : "seller-table fk-user-select-none line"})
47
        print t
48
        table_rows = t.findAll("tr" , {"class" : re.compile('t-row.*')})
49
        print table_rows
50
        for x in table_rows:
51
            print x
52
 
53
    def createData(self,url, redirect_url):
54
        print "Creating soup from flipkart data for %s" %(url)
55
        #redirect_url = redirect_url.replace('www.flipkart.com','163.53.77.21')
56
        print "Redirect url is %s"%(redirect_url)
57
        page=self.response_data.decode("utf-8")
58
        self.soup = BeautifulSoup(page,convertEntities=BeautifulSoup.HTML_ENTITIES)
59
        page = None
60
        self.response_data = None
61
        print "Soup created from flipkart data for %s" %(url)
14333 kshitij.so 62
        print redirect_url
63
        return self.scrape(self.soup,url)
14122 kshitij.so 64
 
65
    def scrape(self,soup,url):
66
        try:
67
            print "data-config"
68
            if soup.find('div',{'class':'seller-table-wrap section'}) is None:
69
                raise
70
            x = json.loads(soup.find('div',{'class':'seller-table-wrap section'})['data-config'])['dataModel']
71
            lines = sorted(x, key=lambda k: k['priceInfo'].get('sellingPrice', 0), reverse=False)
72
            sellingPrice =  float(lines[0]['priceInfo']['sellingPrice'])
73
            try:
74
                offerText = lines[0]['offerInfo']['listingOffers'][0]['description']
75
            except:
76
                offerText = ""
77
            return {'lowestSp':sellingPrice,'inStock':1}
78
        except:
79
            return {'lowestSp':0,'inStock':0}
80
 
81
 
82
 
83
 
84
 
85
if __name__ == '__main__':
86
    scraper = FlipkartProductPageScraper()
14333 kshitij.so 87
    print scraper.read('http://www.flipkart.com/samsung-galaxy-e7/p/itme3un6wdygtqtr?pid=MOBE3UN6NYKGPZPM')