Blame | Last modification | View Log | RSS feed
from BeautifulSoup import BeautifulSoupimport urllib2from sys import exitimport jsonimport reimport tracebackfrom dtr.utils.utils import ungzipResponseheaders = {'User-agent':'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36','Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8','Accept-Language' : 'en-US,en;q=0.8','Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3','Cookie':'T=TI141257426738726661427143281839817329423126740566618323641725716448; __sonar=7237334677420142002; __gads=ID=c8b82101a0e4f451:T=1412574724:S=ALNI_MbPMbEOZj2nAGjM54z8ZHFMqwTOTQ; FK-CMP-DATA=; SN=2.VI11FB3FB6ED9D4693A796AB8C965B3417.SI802C325AC43444858830E870C4FD3324.VS141257426735693951472.1412576209; VID=2.VI11FB3FB6ED9D4693A796AB8C965B3417.1412576209.VS141257426735693951472; NSID=2.SI802C325AC43444858830E870C4FD3324.1412576209.VI11FB3FB6ED9D4693A796AB8C965B3417; __utma=19769839.709301254.1412574234.1412574234.1412574234.1; __utmb=19769839.23.10.1412574234; __utmc=19769839; __utmz=19769839.1412574234.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); s_cc=true; gpv_pn=SellerListing%3AMobile%3AMicromax%20Canvas%20Fire%20A093; gpv_pn_t=no%20value; s_sq=%5B%5BB%5D%5D; pincode=110011; s_ppv=36','Connection':'keep-alive','Accept-Encoding' : 'gzip,deflate,sdch'}searchUrl = "http://www.flipkart.com/search?q="class FlipkartProductPageScraper:def __init__(self):self.count_trials = 0self.redirectCount = 0def read(self, pid):response_data = ""redirect_url = ""try:"""quick fix,need to add it conf"""url = searchUrl+pidprint urlreq = urllib2.Request(url,headers=headers)response = urllib2.urlopen(req)response_data = ungzipResponse(response)print "Fetched response from flipkart for %s" %(url)#redirect_url = response.urlexcept Exception as e:traceback.print_exc()print 'ERROR: ', eprint 'Retrying'self.count_trials += 1if self.count_trials < 3:return self.read(url)self.response_data=response_datareturn self.createData(url,redirect_url)def scrapeRedirectedPage(self,soup,redirect_url):print soupprint redirect_urlt = soup.find("div" , {"class" : "seller-table fk-user-select-none line"})print ttable_rows = t.findAll("tr" , {"class" : re.compile('t-row.*')})print table_rowsfor x in table_rows:print xdef createData(self,url, redirect_url):print "Creating soup from flipkart data for %s" %(url)#redirect_url = redirect_url.replace('www.flipkart.com','163.53.77.21')print "Redirect url is %s"%(redirect_url)page=self.response_data.decode("utf-8")self.soup = BeautifulSoup(page,convertEntities=BeautifulSoup.HTML_ENTITIES)page = Noneself.response_data = Noneprint "Soup created from flipkart data for %s" %(url)print redirect_urlreturn self.scrape(self.soup)def scrape(self,soup):saholicPrice = 0.0cheapestSeller = ''sellingPrice = 0.0try:print "data-config"if soup.find('div',{'class':'seller-table-wrap section'}) is None:raisesellerData = json.loads(soup.find('div',{'class':'seller-table-wrap section'})['data-config'])['dataModel']for seller in sellerData:if (seller['sellerInfo'].get('name')).strip() == 'Saholic':saholicPrice = float(seller['priceInfo'].get('sellingPrice'))lines = sorted(sellerData, key=lambda k: k['priceInfo'].get('sellingPrice', 0), reverse=False)sellingPrice = float(lines[0]['priceInfo']['sellingPrice'])cheapestSeller = (lines[0]['sellerInfo'].get('name')).strip()except:"""No able to parse seller wrap section, probably due to only single seller option"""buyBoxPrice = float(soup.find('span',{'class':'selling-price omniture-field'})['data-evar48'])sellerDiv = soup.find('div',{'class':'seller-badge omniture-field'})cheapestSeller = (sellerDiv.find('a',{'class':'seller-name'}).string)sellingPrice = buyBoxPriceif soup.find('div',{'class':'out-of-stock'}) is not None:inStock = 0else:inStock = 1return {'cheapestSeller':cheapestSeller,'lowestSellingPrice':sellingPrice,'saholicSellingPrice':saholicPrice}if __name__ == '__main__':scraper = FlipkartProductPageScraper()print scraper.read('MOBDUZSYZCA7HDYW')