python实现多线程采集的2个代码例子

 更新时间:2014年07月07日 10:36:23   投稿:junjie  
这篇文章主要介绍了python多线程采集代码例子,使用了Threading、Queue、MySQLdb等模块,需要的朋友可以参考下

代码一:

#!/usr/bin/python
# -*- coding: utf-8 -*-
#encoding=utf-8
 
import threading
import Queue
import sys
import urllib2
import re
import MySQLdb
 
#
# 数据库变量设置
#
DB_HOST = '127.0.0.1'
DB_USER = "XXXX"
DB_PASSWD = "XXXXXXXX"
DB_NAME = "xxxx"
 
#
# 变量设置
#
THREAD_LIMIT = 3
jobs = Queue.Queue(5)
singlelock = threading.Lock()
info = Queue.Queue()
 
def workerbee(inputlist):
    for x in xrange(THREAD_LIMIT):
        print 'Thead {0} started.'.format(x)
        t = spider()
        t.start()
    for i in inputlist:
        try:
            jobs.put(i, block=True, timeout=5)
        except:
            singlelock.acquire()
            print "The queue is full !"
            singlelock.release()
 
    # Wait for the threads to finish
    singlelock.acquire()        # Acquire the lock so we can print
    print "Waiting for threads to finish."
    singlelock.release()        # Release the lock
    jobs.join()              # This command waits for all threads to finish.
    # while not jobs.empty():
    #   print jobs.get()
 
def getTitle(url,time=10):
    response = urllib2.urlopen(url,timeout=time)
    html = response.read()
    response.close()
    reg = r'<title>(.*?)</title>'
    title = re.compile(reg).findall(html)
    # title = title[0].decode('gb2312','replace').encode('utf-8')
    title = title[0]
    return title
 
class spider(threading.Thread):
    def run(self):
        while 1:
            try:
                job = jobs.get(True,1)
                singlelock.acquire()
                title = getTitle(job[1])
                info.put([job[0],title], block=True, timeout=5)
                # print 'This {0} is {1}'.format(job[1],title)
                singlelock.release()
                jobs.task_done()
            except:
                break;
 
if __name__ == '__main__':
    con = None
    urls = []
    try:
        con = MySQLdb.connect(DB_HOST,DB_USER,DB_PASSWD,DB_NAME)
        cur = con.cursor()
        cur.execute('SELECT id,url FROM `table_name` WHERE `status`=0 LIMIT 10')
        rows = cur.fetchall()
        for row in rows:
            # print row
            urls.append([row[0],row[1]])
        workerbee(urls)
        while not info.empty():
            print info.get()
    finally:
        if con:
            con.close()

代码二:

#!/usr/bin/python
# -*- coding: utf-8 -*-
#encoding=utf-8
#Filename:robot.py
 
import threading,Queue,sys,urllib2,re
#
# 变量设置
#
THREAD_LIMIT = 3        #设置线程数
jobs = Queue.Queue(5)      #设置队列长度
singlelock = threading.Lock()    #设置一个线程锁,避免重复调用
 
urls = ['http://games.sina.com.cn/w/n/2013-04-28/1634703505.shtml','http://games.sina.com.cn/w/n/2013-04-28/1246703487.shtml','http://games.sina.com.cn/w/n/2013-04-28/1028703471.shtml','http://games.sina.com.cn/w/n/2013-04-27/1015703426.shtml','http://games.sina.com.cn/w/n/2013-04-26/1554703373.shtml','http://games.sina.com.cn/w/n/2013-04-26/1512703346.shtml','http://games.sina.com.cn/w/n/2013-04-26/1453703334.shtml','http://games.sina.com.cn/w/n/2013-04-26/1451703333.shtml','http://games.sina.com.cn/w/n/2013-04-26/1445703329.shtml','http://games.sina.com.cn/w/n/2013-04-26/1434703322.shtml','http://games.sina.com.cn/w/n/2013-04-26/1433703321.shtml','http://games.sina.com.cn/w/n/2013-04-26/1433703320.shtml','http://games.sina.com.cn/w/n/2013-04-26/1429703318.shtml','http://games.sina.com.cn/w/n/2013-04-26/1429703317.shtml','http://games.sina.com.cn/w/n/2013-04-26/1409703297.shtml','http://games.sina.com.cn/w/n/2013-04-26/1406703296.shtml','http://games.sina.com.cn/w/n/2013-04-26/1402703292.shtml','http://games.sina.com.cn/w/n/2013-04-26/1353703286.shtml','http://games.sina.com.cn/w/n/2013-04-26/1348703284.shtml','http://games.sina.com.cn/w/n/2013-04-26/1327703275.shtml','http://games.sina.com.cn/w/n/2013-04-26/1239703265.shtml','http://games.sina.com.cn/w/n/2013-04-26/1238703264.shtml','http://games.sina.com.cn/w/n/2013-04-26/1231703262.shtml','http://games.sina.com.cn/w/n/2013-04-26/1229703261.shtml','http://games.sina.com.cn/w/n/2013-04-26/1228703260.shtml','http://games.sina.com.cn/w/n/2013-04-26/1223703259.shtml','http://games.sina.com.cn/w/n/2013-04-26/1218703258.shtml','http://games.sina.com.cn/w/n/2013-04-26/1202703254.shtml','http://games.sina.com.cn/w/n/2013-04-26/1159703251.shtml','http://games.sina.com.cn/w/n/2013-04-26/1139703233.shtml']
 
def workerbee(inputlist):
  for x in xrange(THREAD_LIMIT):
    print 'Thead {0} started.'.format(x)
    t = spider()
    t.start()
  for i in inputlist:
    try:
      jobs.put(i, block=True, timeout=5)
    except:
      singlelock.acquire()
      print "The queue is full !"
      singlelock.release()
 
  # Wait for the threads to finish
  singlelock.acquire()    # Acquire the lock so we can print
  print "Waiting for threads to finish."
  singlelock.release()    # Release the lock
  jobs.join()       # This command waits for all threads to finish.
  # while not jobs.empty():
  #  print jobs.get()
 
def getTitle(url,time=10):
  response = urllib2.urlopen(url,timeout=time)
  html = response.read()
  response.close()
  reg = r'<title>(.*?)</title>'
  title = re.compile(reg).findall(html)
  title = title[0].decode('gb2312','replace').encode('utf-8')
  return title
 
class spider(threading.Thread):
  def run(self):
    while 1:
      try:
        job = jobs.get(True,1)
        singlelock.acquire()
        title = getTitle(job)
        print 'This {0} is {1}'.format(job,title)
        singlelock.release()
        jobs.task_done()
      except:
        break;
 
if __name__ == '__main__':
  workerbee(urls)

相关文章

  • windows7 32、64位下python爬虫框架scrapy环境的搭建方法

    windows7 32、64位下python爬虫框架scrapy环境的搭建方法

    这篇文章主要介绍了windows7 32、64位下python爬虫框架scrapy环境的搭建方法,需要的朋友可以参考下
    2018-11-11
  • 一文带你掌握Matplotlib图形绘制

    一文带你掌握Matplotlib图形绘制

    Matplotlib是一个基于Python的绘图库,它提供了一整套与Matlab相似的命令API,非常适合交互式绘图,这篇文章主要给大家介绍了关于Matplotlib图形绘制的相关资料,需要的朋友可以参考下
    2023-09-09
  • 解决python selenium3启动不了firefox的问题

    解决python selenium3启动不了firefox的问题

    今天小编就为大家分享一篇解决python selenium3启动不了firefox的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-10-10
  • 使用Python分析文本数据的词频并词云图可视化

    使用Python分析文本数据的词频并词云图可视化

    这篇文章主要给大家介绍了关于如何使用Python分析文本数据的词频并词云图可视化,文章中有详细的图文介绍和代码示例,对我们的学习或工作有一定的帮助,需要的朋友可以参考下
    2023-09-09
  • python selenium 获取标签的属性值、内容、状态方法

    python selenium 获取标签的属性值、内容、状态方法

    今天小编就为大家分享一篇python selenium 获取标签的属性值、内容、状态方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-06-06
  • python实现顺时针打印矩阵

    python实现顺时针打印矩阵

    这篇文章主要为大家详细介绍了python实现顺时针打印矩阵,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-03-03
  • 基于Python的Houdini插件开发过程详情

    基于Python的Houdini插件开发过程详情

    这篇文章主要介绍了基于Python的Houdini插件开发过程详情,Houdini是基于QT进行的开发,支持 Python、HScript二种脚本进行插件开发,下面文章介绍内容,需要的朋友可以参考一下
    2022-02-02
  • Python科学计算之NumPy入门教程

    Python科学计算之NumPy入门教程

    这篇文章主要介绍了Python科学计算之NumPy,文中给出了详细的介绍与示例代码,对大家的理解具有一定的参考借鉴价值,有需要的朋友可以一起来学习学习。
    2017-01-01
  • jupyter notebook指定启动目录的方法

    jupyter notebook指定启动目录的方法

    这篇文章主要介绍了jupyter notebook指定启动目录的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-03-03
  • 解决Pycharm模块安装慢问题的两种方法

    解决Pycharm模块安装慢问题的两种方法

    很多人在学习Python时,都会使用PyCharm这个编译器,下面这篇文章主要给大家介绍了关于解决Pycharm模块安装慢问题的两种方法,文中通过图文介绍的非常详细,需要的朋友可以参考下
    2022-12-12

最新评论