Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
12363 kshitij.so 1
from BeautifulSoup import BeautifulSoup, NavigableString
2
import re
3
import sys
4
import  datetime
5
import grequests
6
import re
7
 
8
invalid_tags = ['b', 'i', 'u']
9
bestSellers = []
10
 
11
def strip_tags(html, invalid_tags):
12
    soup = BeautifulSoup(html,convertEntities=BeautifulSoup.HTML_ENTITIES)
13
 
14
    for tag in soup.findAll(True):
15
        if tag.name in invalid_tags:
16
            s = ""
17
 
18
            for c in tag.contents:
19
                if not isinstance(c, NavigableString):
20
                    c = strip_tags(unicode(c), invalid_tags)
21
                s += unicode(c)
22
 
23
            tag.replaceWith(s)
24
 
25
    return soup
26
 
27
class AmazonAsyncScraper:
28
    def __init__(self):
29
        self.count_trials = 0
30
 
31
    def read(self, urls, findStore):
32
        returnMap = {}
33
        print datetime.datetime.now()
34
        rs = (grequests.get(u,stream=False) for u in urls)
35
        for x in grequests.map(rs):
36
            soup = BeautifulSoup(x.text,convertEntities=BeautifulSoup.HTML_ENTITIES)
37
            for tag in soup.findAll(True):
38
                if tag.name in invalid_tags:
39
                    s = ""
40
 
41
                    for c in tag.contents:
42
                        if not isinstance(c, NavigableString):
43
                            c = strip_tags(unicode(c), invalid_tags)
44
                        s += unicode(c)
45
 
46
                    tag.replaceWith(s)
47
            x.close()
48
            sellerCount=0
49
            info = []
50
            sellerData = soup.findAll("div" , {"class" : "a-row a-spacing-mini olpOffer"})
12396 kshitij.so 51
            dataLength = len(sellerData)
12363 kshitij.so 52
            for data in sellerData:
53
                tempMap={}
54
                price = data.find('span', attrs={'class' : re.compile('.*olpOfferPrice*')}).find('span').text
55
                unitCost = float(price.replace("Rs.","").replace(",",""))
56
                shippingCost = data.find('p', attrs={'class' : re.compile('.*olpShippingInfo*')}).find('span').text
57
                if "FREE" in shippingCost:
58
                    shippingCost = 0
59
                else:
12402 kshitij.so 60
                    #print "shippingCost= ",float(shippingCost.replace("+Rs.","").replace("Delivery",""))
12363 kshitij.so 61
                    shippingCost = float(shippingCost.replace("+Rs.","").replace("Delivery",""))
62
 
63
                sellerColumn =  data.find('p', attrs={'class' : re.compile('.*olpSellerName*')})
64
                store=""
65
                storeUrl=""
66
                if findStore:
67
                    storeUrl = sellerColumn.find('a')['href']
68
                    temp =  sellerColumn.find('a')
69
                    store = temp.text
70
                    if len(store)==0:
71
                        print storeUrl
72
                        dom_in = storeUrl.find("www.amazon.in")
73
                        print dom_in
74
                        if dom_in ==-1:
75
                            storeUrl="http://amazon.in"+storeUrl
76
                        if storeUrl[storeUrl.rfind('/')+1:]=='AF6E3O0VE0X4D':
77
                            store = 'Saholic'
78
                    if len(store)!=0:
79
                        tempMap['isStoreFront']='True'
80
                    else:
81
                        tempMap['isStoreFront']='False'
82
                    tempMap['storeUrl'] =storeUrl
83
                asinind = x.url.index("offer-listing")
84
                refind = x.url.index("/ref=olp_sort_ps")
85
                asin = x.url[asinind+14:refind].strip()
86
                sellerCount+=1
87
                if sellerCount==1:
88
                    tempMap['sellerName'] = store.strip()
89
                    tempMap['sellerPrice'] = unitCost+shippingCost
90
                if sellerCount==2:
91
                    tempMap['sellerName'] = store.strip()
92
                    tempMap['sellerPrice'] = unitCost+shippingCost
93
                if sellerCount==3:
94
                    tempMap['sellerName'] = store.strip()
95
                    tempMap['sellerPrice'] = unitCost+shippingCost
96
                info.append(tempMap) 
12396 kshitij.so 97
                if sellerCount==3 or sellerCount==dataLength:
12363 kshitij.so 98
                    returnMap[asin] = info 
99
                    break
100
        if findStore:
101
            return self.findStoreFront(returnMap)
102
        else:
103
            return returnMap
104
 
105
    def findStoreFront(self,returnMap):
106
        storeFront={}
107
        for arr in returnMap.itervalues():
108
            for dic in arr:
109
                if dic['isStoreFront']!='True':
110
                    storeFront[dic.get('storeUrl')] =''
111
        rs = (grequests.get(u,stream=False) for u in storeFront.keys())
112
        for x in grequests.map(rs):
113
            soup = strip_tags(x.text,invalid_tags)
114
            x.close
115
            #print x.url.rfind('&me=')
116
            #print x.url[x.url.rfind('&me='):].rfind('&')
117
            mId= x.url[x.url.rfind('&me=')+4:x.url[x.url.rfind('&me='):].rfind('&')+x.url.rfind('&me=')]
118
            sellerName = soup.title.string
119
            #print mId
120
            try:
121
                ind = sellerName.index("@ Amazon.in")
122
                sellerName = sellerName[0:ind].strip()
123
            except:
124
                try:
125
                    ind = sellerName.split(":")
126
                    sellerName = ind[1].strip()
127
                except:
128
                    sellerName =""
129
            #storeFront[re.compile('*'+mId+'.*')] = sellerName
130
            #print mId
131
            #print sellerName
132
            myRe = re.compile('.*'+mId+'.*')
133
            for key in storeFront:
134
                if myRe.match(key):
135
                    #print "Match found ",key
136
                    storeFront[key] = sellerName.strip()
137
            #storeFront.get(re.compile('.*'+mId+'.*'))
138
        for arr in returnMap.itervalues():
139
            #print "arr is ",arr
140
            for dic in arr:
141
                #print "dic ",dic
142
                if dic['isStoreFront']!='True':
143
                    dic['sellerName'] =storeFront.get(dic.get('storeUrl'))
144
                    dic['isStoreFront']='True'
145
 
146
        print "********"
147
        return returnMap
148
 
149
 
150
#        rs = (grequests.get(u,stream=False) for u in urls)
151
#        for x in grequests.map(rs):
152
        #return soup.title.string
153
 
154
 
155
if __name__ == '__main__':
156
    urls=[]
12396 kshitij.so 157
    urls.append("http://amazon.in/gp/offer-listing/B003SNIN9Q/ref=olp_sort_ps")
12363 kshitij.so 158
    urls.append("http://amazon.in/gp/offer-listing")
159
#    asin = []
160
#    for a in amazonlisted:
161
#        asin.append(a.asin)
162
#        urls.append('http://www.amazon.in/gp/offer-listing/'+str(a.asin)+'/ref=olp_sort_ps')
163
#        if len(urls)==50:
164
#            break
165
    print urls
166
    scraper = AmazonAsyncScraper()
12396 kshitij.so 167
    'http://www.amazon.in/gp/offer-listing/B003SNIN9Q/ref=olp_sort_ps'
12363 kshitij.so 168
    print len(urls)
169
    x = scraper.read(urls,True)
170
    print x
171
    print "##################"
172
#    fetched = x.items()
173
#    print list(set(asin) - set(fetched))
174
#    for a,i in x.iteritems():
175
#        print a
176
#        for data in i:
177
#            print data
178
#        print "*********"
179
    #print scraper.createData()
180
    print datetime.datetime.now()