python数据抓取分析的示例代码(python + mongodb)

yipeiwu_com6年前Python爬虫

本文介绍了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(正则表达式)
  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(正则表达式)
  for i in xrange(1,len(p1url) + 1):
   p2url = doc.xpath(正则表达式)
   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设计】。

相关文章

python爬虫项目设置一个中断重连的程序的实现

做爬虫项目时,我们需要考虑一个爬虫在爬取时会遇到各种情况(网站验证,ip封禁),导致爬虫程序中断,这时我们已经爬取过一些数据,再次爬取时这些数据就可以忽略,所以我们需要在爬虫项目中设置一...

python爬虫之遍历单个域名

即使你没听说过“维基百科六度分隔理论”,也很可能听过“凯文 • 贝肯 (Kevin Bacon)的六度分隔值游戏”。在这两个游戏中,目标都是把两 个不相干的主题(在前一种情况...

windows下搭建python scrapy爬虫框架步骤

windows下搭建python scrapy爬虫框架步骤

网络上现有的windows下搭建scrapy教程都比较旧,一般都是咔咔咔安装一堆软件,太麻烦,这是因为scrapy框架用到好多不同的模块,其实查阅最新的官网scrapy文档,在windo...

python抓取网页图片示例(python爬虫)

复制代码 代码如下:#-*- encoding: utf-8 -*-'''Created on 2014-4-24 @author: Leon Wong''' import urllib...

python爬虫的工作原理

1.爬虫的工作原理 网络爬虫,即Web Spider,是一个很形象的名字。把互联网比喻成一个蜘蛛网,那么Spider就是在网上爬来爬去的蜘蛛。网络蜘蛛是通过网页的链接地址来寻找网页的。从...