python+mongodb資料抓取詳細介紹,pythonmongodb

來源:互聯網
上載者:User

python+mongodb資料抓取詳細介紹,pythonmongodb

分享點乾貨!!!

Python資料抓取分析

編程模組:requests,lxml,pymongo,time,BeautifulSoup

首先擷取所有產品的分類網址:

def step():  try:    headers = {      。。。。。      }    r = requests.get(url,headers,timeout=30)    html = r.content    soup = BeautifulSoup(html,"lxml")    url = soup.find_all(Regex)    for i in url:      url2 = i.find_all('a')      for j in url2:         step1url =url + j['href']         print step1url         step2(step1url)  except Exception,e:    print e

我們在產品分類的同時需要確定我們所訪問的地址是產品還是又一個分類的產品地址(所以需要判斷我們訪問的地址是否含有if判斷標誌):

def step2(step1url):  try:    headers = {      。。。。      }    r = requests.get(step1url,headers,timeout=30)    html = r.content    soup = BeautifulSoup(html,"lxml")    a = soup.find('div',id='divTbl')    if a:      url = soup.find_all('td',class_='S-ITabs')      for i in url:        classifyurl = i.find_all('a')        for j in classifyurl:           step2url = url + j['href']           #print step2url           step3(step2url)    else:      postdata(step1url)

當我們if判斷後為真則將第二頁的分類網址擷取到(第一個步驟),否則執行postdata函數,將網頁產品地址抓取!

def producturl(url):  try:    p1url = doc.xpath(Regex)    for i in xrange(1,len(p1url) + 1):      p2url = doc.xpath(Regex)      if len(p2url) > 0:        producturl = url + p2url[0].get('href')        count = db[table].find({'url':producturl}).count()        if count <= 0:            sn = getNewsn()            db[table].insert({"sn":sn,"url":producturl})            print str(sn) + 'inserted successfully'        else:            'url exist'  except Exception,e:    print e

其中為我們所擷取到的產品地址並存入mongodb中,sn作為地址的新id。

下面我們需要在mongodb中通過新id索引來擷取我們的網址並進行訪問,對產品進行資料分析並抓取,將資料更新進資料庫內!

其中用到最多的BeautifulSoup這個模組,但是對於存在於js的價值資料使用BeautifulSoup就用起來很吃力,所以對於js中的資料我推薦使用xpath,但是解析網頁就需要用到HTML.document_fromstring(url)方法來解析網頁。

對於xpath抓取價值資料的同時一定要細心!如果想瞭解xpath就在下面留言,我會儘快回答!

def parser(sn,url):  try:    headers = {      。。。。。。      }    r = requests.get(url, headers=headers,timeout=30)    html = r.content    soup = BeautifulSoup(html,"lxml")    dt = {}    #partno    a = soup.find("meta",itemprop="mpn")    if a:      dt['partno'] = a['content']    #manufacturer    b = soup.find("meta",itemprop="manufacturer")    if b:      dt['manufacturer'] = b['content']    #description    c = soup.find("span",itemprop="description")    if c:      dt['description'] = c.get_text().strip()    #price    price = soup.find("table",class_="table table-condensed occalc_pa_table")    if price:      cost = {}      for i in price.find_all('tr'):        if len(i) > 1:          td = i.find_all('td')          key=td[0].get_text().strip().replace(',','')          val=td[1].get_text().replace(u'\u20ac','').strip()          if key and val:            cost[key] = val      if cost:        dt['cost'] = cost        dt['currency'] = 'EUR'    #quantity    d = soup.find("input",id="ItemQuantity")    if d:      dt['quantity'] = d['value']    #specs    e = soup.find("div",class_="row parameter-container")    if e:      key1 = []      val1= []      for k in e.find_all('dt'):        key = k.get_text().strip().strip('.')        if key:          key1.append(key)      for i in e.find_all('dd'):        val = i.get_text().strip()        if val:          val1.append(val)      specs = dict(zip(key1,val1))    if specs:      dt['specs'] = specs      print dt          if dt:      db[table].update({'sn':sn},{'$set':dt})      print str(sn) + ' insert successfully'      time.sleep(3)    else:      error(str(sn) + '\t' + url)  except Exception,e:    error(str(sn) + '\t' + url)    print "Don't data!"

最後全部程式運行,將價值資料分析處理並存入資料庫中!

以上就是本文關於python+mongodb資料抓取詳細介紹的全部內容,希望對大家有所協助。感興趣的朋友可以繼續參閱本站:Python探索之建立二叉樹、Python探索之修改Python搜尋路徑、淺談python中copy和deepcopy中的區別等,有什麼問題,歡迎留言一起交流討論。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.