python最簡單的爬蟲__python

來源:互聯網
上載者:User

主要5部分:主函數,url管理器,網頁下載器,網頁輸出器,網頁解析器

(用了set,但是下面的代碼並沒有突出set的優勢。後續可改進)

主要入口函數, spider_main:

import url_manager, html_downloader, html_outputer, html_parserclass SpiderMain(object):    def __init__(self):        self.urls = url_manager.UrlManager()        self.downloader = html_downloader.HtmlDownloader()        self.parser = html_parser.HtmlParser()        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()#從隊列中得到一個新的url                print 'craw %d : %s' % (count, new_url)#哪個url正在被爬取                html_cont = self.downloader.download(new_url)#把這個網頁爬下來                new_urls, new_data = self.parser.parse(new_url, html_cont)#解析內部的url和資料                self.urls.add_new_urls(new_urls)#將又爬到的url添加到隊列中                self.outputer.collect_data(new_data)#收集資料                self.outputer.output_html()#列印資料                if count == 10:                    break                count += 1            except Exception as e:                print e                print 'craw failed'if __name__ == "__main__":    root_url = "http://baike.baidu.com/view/21087.htm" #根節點    obj_spider = SpiderMain()    obj_spider.craw(root_url)

url管理器:

class UrlManager(object):    def __init__(self):        self.new_urls = set()        self.old_urls = set()    def get_new_url(self):        new_url = self.new_urls.pop()        self.old_urls.add(new_url)        return new_url    def add_new_url(self, url):#添加新的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

網頁下載器:

import urllib2class HtmlDownloader(object):    def download(self, url):        if url is None:            return None        response = urllib2.urlopen(url)#開啟url,並擷取傳回值        if response.getcode() != 200:            return None        return response.read()#返回網頁的全部內容


網頁解析器:

 

import reimport urlparsefrom bs4 import BeautifulSoupclass HtmlParser(object):    def _get_new_urls(self, page_url, soup):#從一堆文字中擷取url(正則匹配)        new_urls = set()        links = soup.find_all('a', href = re.compile(r"/view/\d+\.htm"))#擷取a標籤中,href為指定格式的標籤全部內容        for link in links:            new_url = link['href']#取其中的href            new_full_url = urlparse.urljoin(page_url, new_url)#拼接成完整連結            new_urls.add(new_full_url)        return new_urls    def _get_new_data(self, page_url, soup):#從一堆文字中擷取資料        res_data = {}#索引值對組合,title索引值對,summary索引值對        #url        res_data['url'] = page_url        #<dd class="lemmaWgt-lemmaTitle-title">        title_node = soup.find('dd', class_ = "lemmaWgt-lemmaTitle-title").find('h1')        res_data['title'] = title_node.get_text()        #print res_data['title']        #<div class="lemma-summary" label-module="lemmaSummary">        summary_node = soup.find('div', class_ = "lemma-summary")        res_data['summary'] = summary_node.get_text()        #print res_data['summary']        return res_data    def parse(self, page_url, html_cont):        if page_url is None or html_cont is None:            return        soup = BeautifulSoup(html_cont, '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("F:\\output.html", 'w')        fout.write("<html>")        fout.write("<body>")        fout.write("<table>")        for data in self.datas:            print data['title']            fout.write("<tr>")            fout.write("<td>%s</td>" % data['url'])            fout.write("<td>%s</td>" % data['title'].encode('utf-8'))            fout.write("<td>%s</td>" % data['summary'].encode('utf-8'))            fout.write("</tr>")        fout.write("</table>")        fout.write("</body>")        fout.write("</html>")        fout.close()


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.