python实现的一只从百度开始不断搜索的小爬虫
admin
2023-07-31 02:02:28
0

文中用到了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() 

相关内容

热门资讯

500 行 Python 代码... 语法分析器描述了一个句子的语法结构,用来帮助其他的应用进行推理。自然语言引入了很多意外的歧义,以我们...
定时清理删除C:\Progra... C:\Program Files (x86)下面很多scoped_dir开头的文件夹 写个批处理 定...
65536是2的几次方 计算2... 65536是2的16次方:65536=2⁶ 65536是256的2次方:65536=256 6553...
scoped_dir32_70... 一台虚拟机C盘总是莫名奇妙的空间用完,导致很多软件没法再运行。经过仔细检查发现是C:\Program...
Mobi、epub格式电子书如... 在wps里全局设置里有一个文件关联,打开,勾选电子书文件选项就可以了。
Prometheus+Graf... 一,Prometheus概述 1,什么是Prometheus?Prometheus是最初在Sound...
python绘图库Matplo... 本文简单介绍了Python绘图库Matplotlib的安装,简介如下: matplotlib是pyt...
pycparser 是一个用... `pycparser` 是一个用 Python 编写的 C 语言解析器。它可以用来解析 C 代码并构...
小程序支付时提示:appid和... [Q]小程序支付时提示:appid和mch_id不匹配 [A]小程序和微信支付没有进行关联,访问“小...
微信小程序使用slider实现... 众所周知哈,微信小程序里面的音频播放是没有进度条的,但最近有个项目呢,客户要求音频要有进度条控制,所...