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+mongodb数据抓取详细介绍的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站:Python探索之创建二叉树Python探索之修改Python搜索路径浅谈python中copy和deepcopy中的区别等,有什么问题,欢迎留言一起交流讨论。

相关文章

简单的抓取淘宝图片的Python爬虫

写了一个抓taobao图片的爬虫,全是用if,for,while写的,比较简陋,入门作品。 从网页http://mm.taobao.com/json/request_top_list.h...

python爬虫爬取监控教务系统的思路详解

python爬虫爬取监控教务系统的思路详解

这几天考了大大小小几门课,教务系统又没有成绩通知功能,为了急切想知道自己挂了多少门,于是我写下这个脚本。 设计思路: 设计思路很简单,首先对已有的成绩进行处理,变为list集合,然后定时...

Python爬虫实战之12306抢票开源

Python爬虫实战之12306抢票开源

今天就和大家一起来讨论一下python实现12306余票查询(pycharm+python3.7),一起来感受一下python爬虫的简单实践 我们说先在浏览器中打开开发者工具(F12),...

python爬虫之自制英汉字典

python爬虫之自制英汉字典

最近在微信公众号中看到有人用Python做了一个爬虫,可以将输入的英语单词翻译成中文,或者把中文词语翻译成英语单词。笔者看到了,觉得还蛮有意思的,因此,决定自己也写一个。 首先我们的爬虫...

python爬虫入门教程--快速理解HTTP协议(一)

python爬虫入门教程--快速理解HTTP协议(一)

前言 爬虫的基本原理是模拟浏览器进行 HTTP 请求,理解 HTTP 协议是写爬虫的必备基础,招聘网站的爬虫岗位也赫然写着熟练掌握HTTP协议规范,写爬虫还不得不先从HTTP协议开始讲...