1. 程式人生 > >Python進階(二十)-Python爬蟲例項講解

Python進階(二十)-Python爬蟲例項講解

分享一下我的偶像大神的人工智慧教程!http://blog.csdn.net/jiangjunshow

也歡迎轉載我的文章,轉載請註明出處 https://blog.csdn.net/mm2zzyzzp

Python進階(二十)-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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51

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
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

網頁下載器

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()
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

網頁解析器

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
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42

網頁輸出器

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>\n')
            # 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>\n' % data['summary'])
            fout.write('</tr>\n')
        fout.write('</table>')
        fout.write('</body>')
        fout.write('</html>')
        fout.close()
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

執行結果

這裡寫圖片描述

  完整程式碼


這裡寫圖片描述

給我偶像的人工智慧教程打call!http://blog.csdn.net/jiangjunshow