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 爬取马蜂窝景点翻页文字评论的实现

python 爬取马蜂窝景点翻页文字评论的实现

使用Chrome、python3.7、requests库和VSCode进行爬取马蜂窝黄鹤楼的文字评论(http://www.mafengwo.cn/poi/5426285.html)。...

Python HTML解析模块HTMLParser用法分析【爬虫工具】

本文实例讲述了Python HTML解析模块HTMLParser用法。分享给大家供大家参考,具体如下: 简介 先简略介绍一下。实际上,HTMLParser是python用来解析HTML的...

解决python爬虫中有中文的url问题

解决python爬虫中有中文的url问题

如果URL中存在中文,而你却不对它做任何处理,他不会达到你所想的那样,因此我们需要将中文部分进行处理,要用到urllib.parse模块中的quote将中文转化成URL所需的编码,url...

Python爬取网易云音乐上评论火爆的歌曲

Python爬取网易云音乐上评论火爆的歌曲

前言 网易云音乐这款音乐APP本人比较喜欢,用户量也比较大,而网易云音乐之所以用户众多和它的歌曲评论功能密不可分,很多歌曲的评论非常有意思,其中也不乏很多感人的评论。但是,网易云音乐并没...

Python3爬取英雄联盟英雄皮肤大图实例代码

Python3爬取英雄联盟英雄皮肤大图实例代码

爬虫思路 初步尝试 我先查看了network,并没有发现有可用的API;然后又用bs4去分析英雄列表页,但是请求到html里面,并没有英雄列表,在英雄列表的节点上,只有“正在加载中”这样...