python yellow page thread crawler

2023-10-09 22:09

本文主要是介绍python yellow page thread crawler,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

把之前的爬虫用python改写了,多线程和队列 来抓取,典型的生产者消费者模式 大笑,用mvc分层来写的抓狂
 
#-*- coding: utf-8 -*-'''
spider.py
Created on 2013-12-21http://www.cn360cn.com/news.aspx?pageno=2
@author: Administrator
'''
import Pager
import Queue
import sys
import time
import threadingtask_queue = Queue.Queue(10)class ProducerThread(threading.Thread):def __init__(self,threadname):threading.Thread.__init__(self)self.name = threadnamedef run(self):for page in xrange(1,50000):url = 'http://www.cn360cn.com/news.aspx?pageno=%d' % pagetask_queue.put(url)print "put %s " % urlclass ConsumerThread(threading.Thread):name = ''url = ''def __init__(self,threadname):threading.Thread.__init__(self)self.name = threadnamedef run(self):while 1:print self.namepage = Pager.Pager()url = task_queue.get()print "get %s " % urltry:page.get_html(url)except Exception as e:print "exception occurred : " , efinally:task_queue.task_done()#控制速度time.sleep(0.5)print "start crawing ...."producer = ProducerThread("crawler producer ....")
producer.setDaemon(True)
producer.start()thread_num = 60
threads = []
for num in xrange(thread_num):print "crawler consumer : %d " % numthreads.append(ConsumerThread("crawler consumer : %d " % num))for num in xrange(thread_num):threads[num].setDaemon(True)threads[num].start()#只到所有任务完成后,才退出主程序
task_queue.join()print "finished ...."
HttpClient.py
# -*- coding:utf-8 -*-import urllib,urllib2class HttpClient:user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36'proxy = ''def __init__(self):urllib2.socket.setdefaulttimeout(8) # timeoutpassdef set_ua(self,user_agent):self.user_agent = user_agentdef set_proxy(self,proxy):self.proxy = proxydef get(self,url,data = {}):headers = { 'User-Agent' : self.user_agent,'Referer': 'http://www.cn360cn.com/','Host':'www.cn360cn.com'}data = urllib.urlencode(data)req = urllib2.Request(url, data, headers)    response = urllib2.urlopen(req)    response = response.read() return responseif __name__ == '__main__':c = HttpClient()print c.get("http://blog.csdn.net/pleasecallmewhy/article/details/8923067")   pager.py
# -*_ coding: utf-8 -*-
'''
Created on 2013-12-21@author: Administrator
'''
import HttpClient
import re
import Daoclass Pager:client = ''dao = ''def __init__(self):self.client = HttpClient.HttpClient()self.dao = Dao.Mysql()passdef get_html(self,url):html = self.client.get(url)#gb2312 to unicode to utf8html = html.decode('gb2312', 'ignore').encode('utf-8')
#        print htmlself.parse_html(html)def parse_html(self,html):page_pattern = re.compile(r'<li>\s*<a.*?>(.*?)<\/a>\s*<div\s+class=tel\s*>\s*电话:(.*?)地址:(.*?)<\/div>\s*<\/li>', re.I | re.M)
#        page_pattern = re.compile(r'<li>\s*<a.*?>(.*?)<\/a>\s*<div\s+class=tel\s*>\s*(.*?)<\/div>\s*<\/li>', re.I | re.M)result =  page_pattern.findall(html)for item in result:
#            print item[0],',',item[1],',',item[2]tag, number, address = item[0],item[1],item[2]number = number.strip()number = number.replace("-", "")tag = tag.strip()address = address.strip()temp = {'tag':tag,'number':number,'address':address}result = self.dao.insert(temp)if __name__ == '__main__':page = Pager()url = 'http://www.cn360cn.com/news.aspx?pageno=2'page.get_html(url)   
Dao.py
'''
Created on 2013-7-20@author: Administrator
'''
import MySQLdb
import config;
import sysclass Mysql:table = 'cn360'conn = ''def __init__(self):self.conn = MySQLdb.connect(host=config.conf['host'], user= config.conf['user'],passwd=config.conf['pwd'],db=config.conf['db'],charset=config.conf['charset'])self.cursor = self.conn.cursor();def insert(self, data):if not data:return Falsesql = "insert ignore into " + self.table + " set "for k, v in enumerate(data):sql += v + "='" + MySQLdb.escape_string(data[v]) + "',"sql = sql.strip(',')
#        print sqlreturn self.execute(sql)def execute(self, sql):if not sql:return Falsetry:self.cursor.execute(sql)self.conn.commit()except:self.conn.rollback();return Falsereturn Truedef get_rows(self, sql):if not sql:return Falseresult = self.execute(sql)if result:return self.cursor.fetchall()return Falsedef update(self, source, filter_array = None):if not source:return Falsesql = "update " + self.table + " set "for k, v in enumerate(source):sql += v + "='" + MySQLdb.escape_string(source[v]) + "',"sql = sql.strip(',')if filter_array:where = ''for k, v in enumerate(filter_array):where += v + "='" + MySQLdb.escape_string(filter_array[v]) + "',"where = where.strip(',')if where:sql += " where " + whereprint sqlreturn self.execute(sql)def delete(self, filter_array = None):if not filter_array:return Falsesql = "delete from " + self.tableif filter_array:where = ''for k, v in enumerate(filter_array):where += v + "='" + MySQLdb.escape_string(filter_array[v]) + "',"where = where.strip(',')if where:sql += " where " + whereprint sqlreturn self.execute(sql)def destroy(self):        self.conn = Noneself.cursor = None


这篇关于python yellow page thread crawler的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/175885

相关文章

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

Python中win32包的安装及常见用途介绍

《Python中win32包的安装及常见用途介绍》在Windows环境下,PythonWin32模块通常随Python安装包一起安装,:本文主要介绍Python中win32包的安装及常见用途的相关... 目录前言主要组件安装方法常见用途1. 操作Windows注册表2. 操作Windows服务3. 窗口操作

Python中re模块结合正则表达式的实际应用案例

《Python中re模块结合正则表达式的实际应用案例》Python中的re模块是用于处理正则表达式的强大工具,正则表达式是一种用来匹配字符串的模式,它可以在文本中搜索和匹配特定的字符串模式,这篇文章主... 目录前言re模块常用函数一、查看文本中是否包含 A 或 B 字符串二、替换多个关键词为统一格式三、提

python常用的正则表达式及作用

《python常用的正则表达式及作用》正则表达式是处理字符串的强大工具,Python通过re模块提供正则表达式支持,本文给大家介绍python常用的正则表达式及作用详解,感兴趣的朋友跟随小编一起看看吧... 目录python常用正则表达式及作用基本匹配模式常用正则表达式示例常用量词边界匹配分组和捕获常用re

python实现对数据公钥加密与私钥解密

《python实现对数据公钥加密与私钥解密》这篇文章主要为大家详细介绍了如何使用python实现对数据公钥加密与私钥解密,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录公钥私钥的生成使用公钥加密使用私钥解密公钥私钥的生成这一部分,使用python生成公钥与私钥,然后保存在两个文

python删除xml中的w:ascii属性的步骤

《python删除xml中的w:ascii属性的步骤》使用xml.etree.ElementTree删除WordXML中w:ascii属性,需注册命名空间并定位rFonts元素,通过del操作删除属... 可以使用python的XML.etree.ElementTree模块通过以下步骤删除XML中的w:as

使用Python绘制3D堆叠条形图全解析

《使用Python绘制3D堆叠条形图全解析》在数据可视化的工具箱里,3D图表总能带来眼前一亮的效果,本文就来和大家聊聊如何使用Python实现绘制3D堆叠条形图,感兴趣的小伙伴可以了解下... 目录为什么选择 3D 堆叠条形图代码实现:从数据到 3D 世界的搭建核心代码逐行解析细节优化应用场景:3D 堆叠图

深度解析Python装饰器常见用法与进阶技巧

《深度解析Python装饰器常见用法与进阶技巧》Python装饰器(Decorator)是提升代码可读性与复用性的强大工具,本文将深入解析Python装饰器的原理,常见用法,进阶技巧与最佳实践,希望可... 目录装饰器的基本原理函数装饰器的常见用法带参数的装饰器类装饰器与方法装饰器装饰器的嵌套与组合进阶技巧

Python中Tensorflow无法调用GPU问题的解决方法

《Python中Tensorflow无法调用GPU问题的解决方法》文章详解如何解决TensorFlow在Windows无法识别GPU的问题,需降级至2.10版本,安装匹配CUDA11.2和cuDNN... 当用以下代码查看GPU数量时,gpuspython返回的是一个空列表,说明tensorflow没有找到

Python get()函数用法案例详解

《Pythonget()函数用法案例详解》在Python中,get()是字典(dict)类型的内置方法,用于安全地获取字典中指定键对应的值,它的核心作用是避免因访问不存在的键而引发KeyError错... 目录简介基本语法一、用法二、案例:安全访问未知键三、案例:配置参数默认值简介python是一种高级编