免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 11393 | 回复: 7
打印 上一主题 下一主题

python 爬虫 某公司的试题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-03-22 08:12 |只看该作者 |倒序浏览
除了logging和自测部分,其它正常。当已经完成这些时,发现某公司又新增加了试题。。。。。。没意思,真没意思。。。。
  1. # coding:utf-8
  2. from time import sleep, ctime
  3. from Queue import Queue
  4. import threading
  5. from BeautifulSoup import BeautifulSoup
  6. import urllib, re, sqlite3, os
  7. from optparse import OptionParser


  8. # 读取url线程类
  9. class readUrlThread(threading.Thread):
  10.     def __init__(self, urlqueue, htmlqueue, readurls, key, deep):
  11.         threading.Thread.__init__(self)
  12.         self.urlqueue = urlqueue
  13.         self.htmlqueue = htmlqueue
  14.         self.key = key
  15.         self.readurls = readurls
  16.         self.deep = deep
  17.         self.urls = readurls
  18.    
  19.     # 取得url
  20.     def geturl(self, urltuple):
  21.         id, url = urltuple
  22.         try:
  23.             html = urllib.urlopen(url).read()
  24.         except UnicodeError, e: # 如果出现Unicode异常 转换后再次放入队列
  25.             self.urlqueue.put((id, url.encode('raw_unicode_escape')))
  26.             return None
  27.         except Exception,e:
  28.             print u'抓取错误:', e
  29.             return None
  30.         if not id >= self.deep: # 判断是否到达层数
  31.             soup = BeautifulSoup(html)
  32.             urlall = soup.findAll('a', onclick=None, href=re.compile('^http:|^/'))
  33.             if url.endswith('/'):
  34.                 url = url[:-1]
  35.             for i in urlall:
  36.                 if i['href'].startswith('/'):
  37.                     i['href'] = url + i['href']
  38.                 if i['href'] not in self.urls: #如果没在已经读取URL列表中时,加入到列表和队列
  39.                     self.urls.append(i['href'])
  40.                     self.urlqueue.put((id+1, i['href']))
  41.         return html
  42.    
  43.     # 过滤字符串
  44.     def htmlfilter(self, url, html):
  45.         if self.key: # 匹配关键字、加入队列
  46.             re_string = '|'.join(key.split())
  47.             if soup.findAll(text=re.compile(re_string)):
  48.                 self.htmlqueue.put((url, key, html))
  49.         else:
  50.             self.htmlqueue.put((url, '', html))
  51.    
  52.     def run(self):
  53.         while True:
  54.             urltuple = self.urlqueue.get()
  55.             id, url = urltuple
  56.             print u'抓取 URL:', self.urlqueue.qsize(), id, url
  57.             html = self.geturl(urltuple)
  58.             if html:
  59.                 self.htmlfilter(url, html)
  60.             self.urlqueue.task_done() # 向url队列发送信号

  61. class writeDatabaseThread(threading.Thread):
  62.     def __init__(self, htmlqueue, sqlitefile):
  63.         threading.Thread.__init__(self)
  64.         self.htmlqueue = htmlqueue
  65.         self.sqlitefile = sqlitefile
  66.    
  67.     def run(self):
  68.         sqliteCon = sqlite3.connect(self.sqlitefile)
  69.         sqliteCon.text_factory = str
  70.         cur=sqliteCon.cursor()
  71.         cur.execute('''
  72.         create table data (
  73.           id INTEGER PRIMARY KEY  AUTOINCREMENT  ,
  74.           url text,
  75.           key text,
  76.           html text
  77.         )
  78.         ''')
  79.         sqliteCon.commit()
  80.         while True:
  81.             url, key, html = self.htmlqueue.get()
  82.             self.htmlqueue.task_done()
  83.             try:
  84.                 cur.execute("insert into data (url,key,html) values (?,?,?)",(url, key, html))
  85.                 sqliteCon.commit()
  86.                 print u'写入:', url, self.htmlqueue.qsize()
  87.             except Exception,e:
  88.                 print u'数据库错误:', e
  89.                 self.htmlqueue.put((url, key, html))
  90.         sqliteCon.close()


  91. def work(url, deep, threads, dbfile, key):
  92.     urlqueue = Queue(0)
  93.     htmlqueue = Queue(0)
  94.     readurls = []
  95.    
  96.     if os.path.isfile(dbfile):
  97.         os.remove(dbfile)
  98.    
  99.     for i in range(threads):
  100.         r = readUrlThread(urlqueue, htmlqueue, readurls, key, deep)
  101.         r.setDaemon(True)
  102.         r.start()
  103.    
  104.     urlqueue.put((1,url))
  105.    
  106.     w = writeDatabaseThread(htmlqueue, dbfile)
  107.     w.setDaemon(True)
  108.     w.start()
  109.    
  110.     urlqueue.join()
  111.     htmlqueue.join()
  112.     print u'运行完成, 链接数量:%d' % len(readurls)

  113. #work('http://www.baidu.com', 2, 50, 'bbe.sqlite','')

  114. if __name__ == '__main__':
  115.     usage = u''
  116.     parser = OptionParser(usage)
  117.     parser.add_option("-u", dest="url", type="string",
  118.                       help=u"指定爬虫开始地址")
  119.     parser.add_option("-d", dest="deep", type="int",
  120.                       help=u"指定爬虫深度")
  121.     parser.add_option("-f", dest="logfile", default="spider.log", type="string",
  122.                       help=u"日志记录文件,默认spider.log")
  123.     parser.add_option("-l", dest="loglevel", default="5", type="int",
  124.                       help=u"日志记录文件记录详细程度,数字越大记录越详细,可选参数")
  125.     parser.add_option("--thread", dest="thread", default="10", type="int",
  126.                       help=u"指定线程池大小,多线程爬取页面,可选参数,默认10")
  127.     parser.add_option("--dbfile", dest="dbfile", type="string",
  128.                       help=u"存放结果数据到指定的数据库(sqlite)文件中")
  129.     parser.add_option("--key", metavar="key", default="", type="string",
  130.                       help=u"页面内的关键词,获取满足该关键词的网页,可选参数,默认为所有页面")
  131.     parser.add_option("--testself", action="store_false", dest="testself", default=True,
  132.                       help=u"程序自测,可选参数")
  133.     (options, args) = parser.parse_args()
  134.    
  135.     if options.testself:
  136.         work(options.url, options.deep, options.thread, options.dbfile, options.key)
  137.     else:
  138.         print '**running standard doctest'
  139.         import doctest, spider1
  140.         doctest.testmod(spider1)
复制代码

论坛徽章:
0
2 [报告]
发表于 2012-03-22 11:59 |只看该作者
我知道是哪个公司了。。。。

论坛徽章:
0
3 [报告]
发表于 2012-03-22 16:02 |只看该作者
我也知道是那个公司了,现在在赵灵儿故乡得公司。。

论坛徽章:
0
4 [报告]
发表于 2012-03-22 16:10 |只看该作者
回复 3# 风间星魂


    You are right...

论坛徽章:
0
5 [报告]
发表于 2013-01-06 02:01 |只看该作者
我靠!!靠靠靠 kkkkkkk

论坛徽章:
0
6 [报告]
发表于 2013-01-06 12:35 |只看该作者
好吧,我还不知道某公司到底是哪个

论坛徽章:
0
7 [报告]
发表于 2013-09-19 11:15 |只看该作者
我也不知道那个公司? 求解

论坛徽章:
1
操作系统版块每日发帖之星
日期:2016-06-12 06:20:00
8 [报告]
发表于 2013-09-19 15:44 |只看该作者
怎么样判断内容更新
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP