python 파충류 실례 상세 설명

6540 단어 python파충
이 박문 은 주로 Python 파충류 의 실례 를 설명 하 는데 중점 은 파충류 기술 구 조 를 포함 하고 파충 류 를 구성 하 는 관건 적 인 모듈 인 URL 관리자,HTML 다운로드 기와 HTML 해상도 기 를 포함한다.
파충류 단순 구조

프로그램 입구 함수(파충류 스케줄 러)

#coding:utf8
import time, datetime

from maya_Spider import url_manager, html_downloader, html_parser, html_outputer


class Spider_Main(object):
 #     
 def __init__(self):
  #  url   
  self.urls = url_manager.UrlManager()
  #  HTML   
  self.downloader = html_downloader.HtmlDownloader()
  #  HTML   
  self.parser = html_parser.HtmlParser()
  #  HTML   
  self.outputer = html_outputer.HtmlOutputer()

 #      
 def craw(self, root_url):
  count = 1
  self.urls.add_new_url(root_url)
  while self.urls.has_new_url():
   try:
    new_url = self.urls.get_new_url()
    print('craw %d : %s' % (count, new_url))
    html_content = self.downloader.download(new_url)
    new_urls, new_data = self.parser.parse(new_url, html_content)
    self.urls.add_new_urls(new_urls)
    self.outputer.collect_data(new_data)

    if count == 10:
     break

    count = count + 1
   except:
    print('craw failed')

  self.outputer.output_html()

if __name__ == '__main__':
 #      
 root_url = 'http://baike.baidu.com/view/21087.htm'
 #    
 print('    ..............')
 start_time = datetime.datetime.now()
 obj_spider = Spider_Main()
 obj_spider.craw(root_url)
 #    
 end_time = datetime.datetime.now()
 print('   :%ds'% (end_time - start_time).seconds)
URL 관리자

class UrlManager(object):
 def __init__(self):
  self.new_urls = set()
  self.old_urls = set()

 def add_new_url(self, url):
  if url is None:
   return
  if url not in self.new_urls and url not in self.old_urls:
   self.new_urls.add(url)

 def add_new_urls(self, urls):
  if urls is None or len(urls) == 0:
   return
  for url in urls:
   self.add_new_url(url)

 def has_new_url(self):
  return len(self.new_urls) != 0

 def get_new_url(self):
  new_url = self.new_urls.pop()
  self.old_urls.add(new_url)
  return new_url
웹 페이지 다운 로 더

import urllib
import urllib.request

class HtmlDownloader(object):

 def download(self, url):
  if url is None:
   return None

  #        ,      csdn   
  user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
  headers = {'User-Agent':user_agent}
  #    
  req = urllib.request.Request(url,headers=headers)
  #    
  response = urllib.request.urlopen(req)
  #python3 urllib.read    bytes  ,  string,      string  , bytes.decode  
  return response.read().decode()
웹 페이지 해석 기

import re
import urllib
from urllib.parse import urlparse

from bs4 import BeautifulSoup

class HtmlParser(object):

 def _get_new_urls(self, page_url, soup):
  new_urls = set()
  #/view/123.htm
  links = soup.find_all('a', href=re.compile(r'/item/.*?'))
  for link in links:
   new_url = link['href']
   new_full_url = urllib.parse.urljoin(page_url, new_url)
   new_urls.add(new_full_url)
  return new_urls

 #    、  
 def _get_new_data(self, page_url, soup):
  #    
  res_data = {}
  #url
  res_data['url'] = page_url
  #<dd class="lemmaWgt-lemmaTitle-title"><h1>Python</h1>      
  title_node = soup.find('dd', class_="lemmaWgt-lemmaTitle-title").find('h1')
  print(str(title_node.get_text()))
  res_data['title'] = str(title_node.get_text())
  #<div class="lemma-summary" label-module="lemmaSummary">
  summary_node = soup.find('div', class_="lemma-summary")
  res_data['summary'] = summary_node.get_text()

  return res_data

 def parse(self, page_url, html_content):
  if page_url is None or html_content is None:
   return None

  soup = BeautifulSoup(html_content, 'html.parser', from_encoding='utf-8')
  new_urls = self._get_new_urls(page_url, soup)
  new_data = self._get_new_data(page_url, soup)
  return new_urls, new_data
웹 페이지 출력 기

class HtmlOutputer(object):

 def __init__(self):
  self.datas = []

 def collect_data(self, data):
  if data is None:
   return
  self.datas.append(data )

 def output_html(self):
  fout = open('maya.html', 'w', encoding='utf-8')
  fout.write("<head><meta http-equiv='content-type' content='text/html;charset=utf-8'></head>")
  fout.write('<html>')
  fout.write('<body>')
  fout.write('<table border="1">')
  # <th width="5%">Url</th>
  fout.write('''<tr style="color:red" width="90%">
     <th>Theme</th>
     <th width="80%">Content</th>
     </tr>''')
  for data in self.datas:
   fout.write('<tr>
') # fout.write('\t<td>%s</td>' % data['url']) fout.write('\t<td align="center"><a href=\'%s\'>%s</td>' % (data['url'], data['title'])) fout.write('\t<td>%s</td>
' % data['summary']) fout.write('</tr>
') fout.write('</table>') fout.write('</body>') fout.write('</html>') fout.close()
실행 결과

첨부:전체 코드
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기