发布于 2014-09-27 12:20:01 | 174 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Python教程,程序狗速度看过来!

Python编程语言

Python 是一种面向对象、解释型计算机程序设计语言,由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年。Python语法简洁而清晰,具有丰富和强大的类库。它常被昵称为胶水语言,它能够把用其他语言制作的各种模块(尤其是C/C++)很轻松地联结在一起。


本文是一个用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() 

 



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务