Subversion Repositories SmartDukaan

Rev

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