Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
11934 kshitij.so 1
import urllib2
2
from BeautifulSoup import BeautifulSoup, NavigableString
3
import re
4
import sys
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
        request = urllib2.Request(url)
31
        request.add_header('User-Agent', 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.218 Safari/535.1')
32
        opener = urllib2.build_opener()
33
        response_data = ""
34
        try:
35
            response_data = opener.open(request).read()
36
 
37
        except urllib2.HTTPError as e:
38
            print 'ERROR: ', e
39
            print 'Retrying'
40
            self.count_trials += 1
41
 
42
            if self.count_trials < 3:
43
                return self.read(url)
44
 
45
        self.response_data=response_data
46
 
47
    def createData(self):
48
        self.soup = strip_tags(self.response_data,invalid_tags)
12197 kshitij.so 49
        self.response_data =None
11934 kshitij.so 50
        return self.scrape(self.soup)
51
 
52
 
53
    def scrape(self,soup):
54
        sellerData = soup.findAll("div" , {"class" : "a-row a-spacing-mini olpOffer"})
55
        for data in sellerData:
56
            print "sellerData****"
57
            price = data.find('span', attrs={'class' : re.compile('.*olpOfferPrice*')}).find('span').text
58
            print "Unit cost= ",float(price.replace("Rs.","").replace(",",""))
59
            unitCost = float(price.replace("Rs.","").replace(",",""))
60
            shippingCost = data.find('p', attrs={'class' : re.compile('.*olpShippingInfo*')}).find('span').text
61
            if "FREE" in shippingCost:
62
                print "shippingCost=0"
63
                shippingCost = 0
64
            else:
65
                print "shippingCost= ",float(shippingCost.replace("+Rs.","").replace("Delivery",""))
66
                shippingCost = float(shippingCost.replace("+Rs.","").replace("Delivery",""))
67
 
68
            sellerColumn =  data.find('p', attrs={'class' : re.compile('.*olpSellerName*')})
69
            print "Seller info ",sellerColumn
70
            ratingColumn = data.find('p', attrs={'class' : 'a-spacing-small'}).find('a').contents[0]
71
            print "Rating info ",ratingColumn
72
            print "***********************"
73
            return unitCost+shippingCost
74
 
75
    def getBestSellers(self,soup):
76
        global bestSellers
77
        bestSellerData = soup.findAll("div" , {"class" : "zg_itemImmersion"})
78
        for data in bestSellerData:
79
            temp = {}
80
            rankVal = data.find('span', attrs={'class' : 'zg_rankNumber'}).text
81
            print "Rank = ",rankVal.lstrip()
82
            productUrl = data.find('a')['href']
83
            print "Product URL = ",productUrl.lstrip().replace("\n","")
84
            productUrl = productUrl.replace("http://www.amazon.in/","").lstrip()
85
            ind = productUrl.rindex("/dp/")
86
            productName = productUrl[0:productUrl.rindex("/dp/")]
87
            print "Product Name = ",productName
88
            asin = productUrl[ind+4: productUrl.rindex("/ref=")]
89
            print "Asin = ",asin
90
            print "**********************"
91
            temp['Rank'] = rankVal.lstrip().replace(".","")
92
            temp['Url'] = productUrl.lstrip().replace("\n","")
93
            temp['Product Name'] = productUrl[0:productUrl.rindex("/dp/")]
94
            temp['Asin'] = productUrl[ind+4: productUrl.rindex("/ref=")]
95
            bestSellers.append(temp)
96
 
97
 
98
if __name__ == '__main__':
99
    scraper = AmazonScraper()
100
    scraper.read('http://www.amazon.in/gp/offer-listing/B001D0ROGO/ref=olp_sort_ps')
101
    print scraper.createData()
102