python实现的一只从百度开始不断搜索的小爬虫


Posted in Python onAugust 13, 2013

文中用到了BeautifulSoup这个库, 目的是处理html文档分析的, 因为我只是提取了title的关键字,所以可以用正则表达式代替, 还有一个库是jieba, 这个库是中文分词的作用, 再有一个库是 chardet, 用来判断字符的编码, 本想多线程的, 但是自认为被搞糊涂了,就放弃了

#coding:utf-8
import re
import urllib
import urllib2
import sys
import time
import Queue 
import thread
import threading
import jieba
import chardet
from BeautifulSoup import BeautifulSoup as BS

DEEP = 1000
LOCK = threading.Lock()
PATH = "c:\\test\\"
urlQueue = Queue.Queue()
def pachong():
 url = 'http://www.baidu.com'
 return url
def getPageUrl(html):
 reUrl = re.compile(r'<\s*[Aa]{1}\s+[^>]*?[Hh][Rr][Ee][Ff]\s*=\s*[\"\']?([^>\"\']+)[\"\']?.*?>')
 urls = reUrl.findall(html)
 for url in urls:
  if len(url) > 10:
   if url.find('javascript') == -1:
    urlQueue.put(url)
def getContents(url):
 try:
  url = urllib2.quote(url.split('#')[0].encode('utf-8'), safe = "%/:=&?~#+!$,;'@()*[]")
  req = urllib2.urlopen(url)
  res = req.read()
  code = chardet.detect(res)['encoding']
  #print
  #print code
  res = res.decode(str(code), 'ignore')
  res = res.encode('gb2312', 'ignore')
  code = chardet.detect(res)['encoding']
  #print code
  #print res
  return res
 except urllib2.HTTPError, e:
  print e.code
  return None
 except urllib2.URLError, e:
  print str(e)
  return None
def writeToFile(html, url):
 fp = file(PATH + str(time.time()) + '.html', 'w')
 fp.write(html)
 fp.close()
 
def getKeyWords(html):
 code = chardet.detect(html)['encoding']
 if code == 'ISO-8859-2':
  html.decode('gbk', 'ignore').encode('gb2312', 'ignore')
 code = chardet.detect(html)['encoding']
 soup = BS(html, fromEncoding="gb2312")
 titleTag = soup.title
 titleKeyWords = titleTag.contents[0]
 cutWords(titleKeyWords)
def cutWords(contents):
 print contents
 res = jieba.cut_for_search(contents)
 res = '\n'.join(res)
 print res
 res = res.encode('gb2312')
 keyWords = file(PATH + 'cutKeyWors.txt', 'a')
 keyWords.write(res)
 keyWords.close()
def start():
 while urlQueue.empty() == False:
  url = urlQueue.get()
  html = getContents(url)
  getPageUrl(html)
  getKeyWords(html)
  #writeToFile(html, url)
  
if __name__ == '__main__':
 startUrl = pachong()
 urlQueue.put(startUrl)
 start() 
Python 相关文章推荐
详解在Python程序中自定义异常的方法
Oct 16 Python
深入讲解Java编程中类的生命周期
Feb 05 Python
Python数组定义方法
Apr 13 Python
python制作爬虫爬取京东商品评论教程
Dec 16 Python
Python第三方库xlrd/xlwt的安装与读写Excel表格
Jan 21 Python
Python面向对象之继承代码详解
Jan 29 Python
如何在Django项目中引入静态文件
Jul 26 Python
基于python3 的百度图片下载器的实现代码
Nov 05 Python
python实现将一维列表转换为多维列表(numpy+reshape)
Nov 29 Python
浅谈PyTorch中in-place operation的含义
Jun 27 Python
Python连接Impala实现步骤解析
Aug 04 Python
python xlwt模块的使用解析
Apr 13 Python
python用于url解码和中文解析的小脚本(python url decoder)
Aug 11 #Python
python 合并文件的具体实例
Aug 08 #Python
python备份文件以及mysql数据库的脚本代码
Jun 10 #Python
Python 变量类型及命名规则介绍
Jun 08 #Python
Python 字符串操作实现代码(截取/替换/查找/分割)
Jun 08 #Python
python strip()函数 介绍
May 24 #Python
Python的词法分析与语法分析
May 18 #Python
You might like
用header 发送cookie的php代码
2007/03/16 PHP
CI框架验证码CAPTCHA辅助函数用法实例
2014/11/05 PHP
php通过array_unshift函数添加多个变量到数组前端的方法
2015/03/18 PHP
php使用simplexml_load_file加载XML文件并显示XML的方法
2015/03/19 PHP
PHP实现的简单分页类及用法示例
2016/05/06 PHP
PHP实现的简单sha1加密功能示例
2017/08/27 PHP
PHP结合Ffmpeg快速搭建流媒体服务的实践记录
2018/10/31 PHP
PHP实现基于状态的责任链审批模式详解
2019/05/31 PHP
Yii框架参数配置文件params用法实例分析
2019/09/11 PHP
php ZipArchive实现多文件打包下载实例
2019/10/31 PHP
Apply an AutoFormat to an Excel Spreadsheet
2007/06/12 Javascript
JavaScript获取GridView中用户点击控件的行号,列号
2009/04/14 Javascript
AeroWindow 基于JQuery的弹出窗口插件
2011/06/27 Javascript
node.js适合游戏后台开发吗?
2014/09/03 Javascript
jQuery使用removeClass方法删除元素指定Class的方法
2015/03/26 Javascript
layer弹出子iframe层父子页面传值的实现方法
2018/11/22 Javascript
vue-test-utils初使用详解
2019/05/23 Javascript
微信小程序防止多次点击跳转(函数节流)
2019/09/19 Javascript
JavaScript实现简单的计算器
2020/01/16 Javascript
python使用mailbox打印电子邮件的方法
2015/04/30 Python
Python 递归函数详解及实例
2016/12/27 Python
Pycharm+Scrapy安装并且初始化项目的方法
2019/01/15 Python
PyQt5实现类似别踩白块游戏
2019/01/24 Python
如何用C代码给Python写扩展库(Cython)
2019/05/17 Python
django 单表操作实例详解
2019/07/30 Python
pycharm下pyqt4安装及环境配置的教程
2020/04/24 Python
Django获取model中的字段名和字段的verbose_name方式
2020/05/19 Python
python 实时调取摄像头的示例代码
2020/11/25 Python
机械设计专业应届生求职信
2013/11/21 职场文书
护理专业大学生自我推荐信
2014/01/25 职场文书
同学聚会老师邀请函
2014/01/28 职场文书
大学新生军训方案
2014/05/03 职场文书
省级青年文明号申报材料
2014/05/23 职场文书
党性教育心得体会
2014/09/03 职场文书
实习单位证明范例
2014/11/17 职场文书
2016春季运动会开幕词
2016/03/04 职场文书