Subversion Repositories SmartDukaan

Rev

Rev 12363 | Rev 12402 | 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:
60
                    print "shippingCost= ",float(shippingCost.replace("+Rs.","").replace("Delivery",""))
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
            print "arr is ",arr
109
            for dic in arr:
110
                print "dic ",dic
111
                if dic['isStoreFront']!='True':
112
                    storeFront[dic.get('storeUrl')] =''
113
        rs = (grequests.get(u,stream=False) for u in storeFront.keys())
114
        for x in grequests.map(rs):
115
            soup = strip_tags(x.text,invalid_tags)
116
            x.close
117
            #print x.url.rfind('&me=')
118
            #print x.url[x.url.rfind('&me='):].rfind('&')
119
            mId= x.url[x.url.rfind('&me=')+4:x.url[x.url.rfind('&me='):].rfind('&')+x.url.rfind('&me=')]
120
            sellerName = soup.title.string
121
            #print mId
122
            try:
123
                ind = sellerName.index("@ Amazon.in")
124
                sellerName = sellerName[0:ind].strip()
125
            except:
126
                try:
127
                    ind = sellerName.split(":")
128
                    sellerName = ind[1].strip()
129
                except:
130
                    sellerName =""
131
            #storeFront[re.compile('*'+mId+'.*')] = sellerName
132
            #print mId
133
            #print sellerName
134
            myRe = re.compile('.*'+mId+'.*')
135
            for key in storeFront:
136
                if myRe.match(key):
137
                    #print "Match found ",key
138
                    storeFront[key] = sellerName.strip()
139
            #storeFront.get(re.compile('.*'+mId+'.*'))
140
        for arr in returnMap.itervalues():
141
            #print "arr is ",arr
142
            for dic in arr:
143
                #print "dic ",dic
144
                if dic['isStoreFront']!='True':
145
                    dic['sellerName'] =storeFront.get(dic.get('storeUrl'))
146
                    dic['isStoreFront']='True'
147
 
148
        print "********"
149
        return returnMap
150
 
151
 
152
#        rs = (grequests.get(u,stream=False) for u in urls)
153
#        for x in grequests.map(rs):
154
        #return soup.title.string
155
 
156
 
157
if __name__ == '__main__':
158
    urls=[]
12396 kshitij.so 159
    urls.append("http://amazon.in/gp/offer-listing/B003SNIN9Q/ref=olp_sort_ps")
12363 kshitij.so 160
    urls.append("http://amazon.in/gp/offer-listing")
161
#    asin = []
162
#    for a in amazonlisted:
163
#        asin.append(a.asin)
164
#        urls.append('http://www.amazon.in/gp/offer-listing/'+str(a.asin)+'/ref=olp_sort_ps')
165
#        if len(urls)==50:
166
#            break
167
    print urls
168
    scraper = AmazonAsyncScraper()
12396 kshitij.so 169
    'http://www.amazon.in/gp/offer-listing/B003SNIN9Q/ref=olp_sort_ps'
12363 kshitij.so 170
    print len(urls)
171
    x = scraper.read(urls,True)
172
    print x
173
    print "##################"
174
#    fetched = x.items()
175
#    print list(set(asin) - set(fetched))
176
#    for a,i in x.iteritems():
177
#        print a
178
#        for data in i:
179
#            print data
180
#        print "*********"
181
    #print scraper.createData()
182
    print datetime.datetime.now()