国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python實現的一只從百度開始不斷搜索的小爬蟲

2019-11-25 18:39:02
字體:
來源:轉載
供稿:網友

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 辽阳县| 凤台县| 武夷山市| 万荣县| 博野县| 德清县| 淳化县| 射阳县| 普宁市| 乌鲁木齐市| 林西县| 西贡区| 高陵县| 东城区| 和田县| 越西县| 资源县| 哈密市| 湖北省| 洛南县| 朝阳区| 高雄县| 汉沽区| 霍山县| 孝昌县| 正安县| 乌鲁木齐县| 兰坪| 剑河县| 贵州省| 大宁县| 巨鹿县| 建瓯市| 甘南县| 沾益县| 阿瓦提县| 宝应县| 襄垣县| 苗栗市| 阿瓦提县| 灵川县|