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

yipeiwu_com4年前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爬虫入门教程之糗百图片爬虫代码分享

学习python少不了写爬虫,不仅能以点带面地学习、练习使用python,爬虫本身也是有用且有趣的,大量重复性的下载、统计工作完全可以写一个爬虫程序完成。用python写爬虫需要pytho...

解决Python 爬虫URL中存在中文或特殊符号无法请求的问题

这种问题,初学者应该都会遇到,分享给大家做个参考! from urllib.parse import quote import string #解决请求路径中含义中文或特殊字符 u...

python爬虫中get和post方法介绍以及cookie作用

首先确定你要爬取的目标网站的表单提交方式,可以通过开发者工具看到。这里推荐使用chrome。 这里我用163邮箱为例 打开工具后再Network中,在Name选中想要了解的网站,右侧...

Python的爬虫包Beautiful Soup中用正则表达式来搜索

Beautiful Soup使用时,一般可以通过指定对应的name和attrs去搜索,特定的名字和属性,以找到所需要的部分的html代码。 但是,有时候,会遇到,对于要处理的内容中,其n...

python爬虫实现中英翻译词典

本文实例为大家分享了python爬虫实现中英翻译词典的具体代码,供大家参考,具体内容如下 通过根据某平台的翻译资源,提取出翻译信息,并展示出来,包括输入,翻译,输出三个过程,主要利用py...