Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
14307 kshitij.so 1
import urllib2
2
from BeautifulSoup import BeautifulSoup, NavigableString
3
import re
14759 kshitij.so 4
from dtr.utils.utils import fetchResponseUsingProxy
14307 kshitij.so 5
 
6
invalid_tags = ['b', 'i', 'u']
7
bestSellers = []
8
 
9
def strip_tags(html, invalid_tags):
10
    soup = BeautifulSoup(html,convertEntities=BeautifulSoup.HTML_ENTITIES)
11
 
12
    for tag in soup.findAll(True):
13
        if tag.name in invalid_tags:
14
            s = ""
15
 
16
            for c in tag.contents:
17
                if not isinstance(c, NavigableString):
18
                    c = strip_tags(unicode(c), invalid_tags)
19
                s += unicode(c)
20
 
21
            tag.replaceWith(s)
22
 
23
    return soup
24
 
25
class AmazonScraper:
26
    def __init__(self):
27
        self.count_trials = 0
28
 
29
    def read(self, url):
30
        response_data = ""
31
        try:
14759 kshitij.so 32
            response_data = fetchResponseUsingProxy(url)
33
        except Exception as e:
14307 kshitij.so 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()
43
 
44
    def createData(self):
45
        self.soup = strip_tags(self.response_data,invalid_tags)
46
        self.response_data =None
47
        return self.scrape(self.soup)
48
 
49
 
50
    def scrape(self,soup):
51
        try:
52
            sellerData = soup.find("span" , {"id" : "priceblock_dealprice"})
53
            dealPrice = float(sellerData.text.replace("Rs.","").replace(",",""))
54
        except:
55
            dealPrice = 0.0
56
        try:
57
            dealAvailablity =  soup.find('div',{'id':'deal_availability'})
58
            dealStatus = dealAvailablity.find('span',{'id':re.compile('dealStatusAvailability_*')})
59
            dealStatus = float(dealStatus.text.replace("%","").replace(",",""))
60
        except:
61
            dealStatus = 100
62
 
63
        if dealStatus < 100 and dealPrice > 0:
64
            return dealPrice
65
        else:
66
            return 0.0
67
 
68
if __name__ == '__main__':
69
    scraper = AmazonScraper()
70
    print scraper.read('http://www.amazon.in/gp/product/B00FXLCLTO')
71