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基础教程之类class定义使用方法
Feb 20 Python
python使用win32com在百度空间插入html元素示例
Feb 20 Python
Python中set与frozenset方法和区别详解
May 23 Python
python爬虫之urllib库常用方法用法总结大全
Nov 14 Python
Python中collections模块的基本使用教程
Dec 07 Python
python json load json 数据后出现乱序的解决方案
Feb 27 Python
python中读入二维csv格式的表格方法详解(以元组/列表形式表示)
Apr 24 Python
Keras: model实现固定部分layer,训练部分layer操作
Jun 28 Python
详解pycharm2020.1.1专业版安装指南(推荐)
Aug 07 Python
使用Selenium实现微博爬虫(预登录、展开全文、翻页)
Apr 13 Python
Python Django框架介绍之模板标签及模板的继承
May 27 Python
Python pandas之求和运算和非空值个数统计
Aug 07 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
php+webSoket实现聊天室示例代码(附源码)
2017/02/17 PHP
js+CSS 图片等比缩小并垂直居中实现代码
2008/12/01 Javascript
jquery 图片轮换效果
2010/07/29 Javascript
在浏览器窗口上添加遮罩层的方法
2012/11/12 Javascript
JAVASCRIPT代码编写俄罗斯方块网页版
2015/11/26 Javascript
JavaScript图像延迟加载库Echo.js
2016/04/05 Javascript
JavaScript常见的五种数组去重的方式
2016/12/15 Javascript
配置nodejs环境的方法
2017/05/13 NodeJs
浅谈react.js中实现tab吸顶效果的问题
2017/09/06 Javascript
微信网页授权并获取用户信息的方法
2018/07/30 Javascript
JavaScript实用代码小技巧
2018/08/23 Javascript
Vue.js 事件修饰符的使用教程
2018/11/01 Javascript
jquery实现动态改变css样式的方法分析
2019/05/27 jQuery
vue-cli创建的项目中的gitHooks原理解析
2020/02/14 Javascript
Python和Perl绘制中国北京跑步地图的方法
2016/03/03 Python
浅析Python的web.py框架中url的设定方法
2016/07/11 Python
Python 中Pickle库的使用详解
2018/02/24 Python
Python3 tkinter 实现文件读取及保存功能
2019/09/12 Python
Python semaphore evevt生产者消费者模型原理解析
2020/03/18 Python
pycharm导入源码的具体步骤
2020/08/04 Python
锐步美国官方网站:Reebok美国
2018/01/10 全球购物
美国时尚假发购物网站:Wigsbuy
2019/04/06 全球购物
NYX Professional Makeup英国官网:美国平价专业彩妆品牌
2019/11/13 全球购物
Fossil德国官网:化石手表、手袋、珠宝及配件
2019/12/07 全球购物
英国著名药妆店:Superdrug
2021/02/13 全球购物
设置器与访问器的定义以及各自特点
2016/01/08 面试题
《掌声》教学反思
2014/02/23 职场文书
旅行社各个岗位职责
2014/03/15 职场文书
学生操行评语大全
2014/04/24 职场文书
教师群众路线心得体会
2014/11/04 职场文书
留学推荐信英文范文
2015/03/26 职场文书
保姆聘用合同
2015/09/21 职场文书
90条交通安全宣传标语
2019/10/12 职场文书
Python基础之元组与文件知识总结
2021/05/19 Python
pytorch 6 batch_train 批训练操作
2021/05/28 Python
Go语言空白表示符_的实例用法
2021/07/04 Golang