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

yipeiwu_com5年前Python爬虫


文中用到了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 selenium 爬取网易云音乐歌单名

详解python selenium 爬取网易云音乐歌单名

目标网站: 首先获取第一页的数据,这里关键要切换到iframe里 打印一下 获取剩下的页数,这里在点击下一页之前需要设置一个延迟,不然会报错。 结果: 一共37页,爬取完...

python爬虫 爬取超清壁纸代码实例

python爬虫 爬取超清壁纸代码实例

简介 壁纸的选择其实很大程度上能看出电脑主人的内心世界,有的人喜欢风景,有的人喜欢星空,有的人喜欢美女,有的人喜欢动物。然而,终究有一天你已经产生审美疲劳了,但你下定决定要换壁纸的时候...

python2.7实现爬虫网页数据

python2.7实现爬虫网页数据

最近刚学习Python,做了个简单的爬虫,作为一个简单的demo希望帮助和我一样的初学者。 代码使用python2.7做的爬虫  抓取51job上面的职位名,公司名,薪资,发布...

python爬虫(入门教程、视频教程) 原创

python的版本经过了python2.x和python3.x等版本,无论哪种版本,关于python爬虫相关的知识是融会贯通的,【听图阁-专注于Python设计】关于爬虫这个方便整理过很...

python制作爬虫爬取京东商品评论教程

python制作爬虫爬取京东商品评论教程

本篇文章是python爬虫系列的第三篇,介绍如何抓取京东商城商品评论信息,并对这些评论信息进行分析和可视化。下面是要抓取的商品信息,一款女士文胸。这个商品共有红色,黑色和肤色三种颜色,...