简单爬虫——爬取百度百科总结

在慕课网学习简单爬虫来爬取百度百科的总结:


一、逻辑:根据根url: http://baike.baidu.com/item/Python,通过python的第三方插件Beautiful Soup来获取页面的html代码,找到我们需要的信息,这里我们需要的信息是:

#

Python

#
中的h1标签、类名为lemma-summary的div内的内容。

有一个url管理器,来获取和管理所有需要爬取的链接a,比如在这里我们先获取http://baike.baidu.com/item/Python这个页面的所有a标签,将其存入一个容器(new_urls)中,然后依次爬取这个容器中的所有url,每爬一次,把爬取过的url从这个容器中删去,加入到old_urls容器中, 并且加入到new_urls时要判断这个url是否在new_urls和old_urls已经存在,若存在,不加入,防止重复爬取。然后通过页面下载器利用urllib2下载我们需要的页面代码,页面解析器html_parse利用beautifulsoup获取我们需要的数据。

二、具体代码:

1.主函数 spider_main.py

#_*_coding:utf-8_*_
from baike_spider2 import url_manager,html_downloader,html_parser,html_outputer

class SpiderMain(object):
    def __init__(self):
        self.urls = url_manager.UrlManager()
        self.downloader = html_downloader.HtmlDownloader()
        self.parser = html_parser.HtmlPsrser()
        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_cont = self.downloader.download(new_url)
                new_urls, new_data = self.parser.parse(new_url, html_cont)
                self.urls.add_new_urls(new_urls)
                self.outputer.collect_data(new_data)

                if count == 100:
                    break
                count = count + 1

            except:
                print 'craw fail'

        self.outputer.output_html()


if __name__=="__main__":
    # 爬虫入口页面
    root_url = 'http://baike.baidu.com/item/Python'
    obj_spider = SpiderMain()
    # 启动爬虫
    obj_spider.craw(root_url)

2.页面下载器 html_downloader.py

#_*_coding:utf-8_*_
import urllib2

class HtmlDownloader(object):

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

        response = urllib2.urlopen(url)

        if response.getcode() != 200:
            return None

        return response.read()

3.页面输出器 html_outputer.py

#_*_coding:utf-8_*_

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('output.html', 'w')

        fout.write("")
        fout.write("")
        fout.write("")

        for data in self.datas:
            fout.write("")
            fout.write("" % data['url'].encode('utf-8'))
            fout.write("" % data['title'].encode('utf-8'))
            fout.write("" % data['summary'].encode('utf-8'))
            fout.write("")

        fout.write("
%s%s%s
") fout.write("") fout.write("")

4.页面解析器 html_parser.py

#_*_coding:utf-8_*_
from bs4 import  BeautifulSoup
import urlparse
import re

class HtmlPsrser(object):

    def _get_new_urls(self, page_url, soup):
        new_urls = set()
        # links = soup.find_all('a', href=re.compile(r"/item/\d+\.html"))
        links = soup.find_all('a', href=re.compile(r"/item/(.*)"))
        for link in links:
            new_url = link['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 = {}

        res_data['url'] = page_url

        #

Python

title_node = soup.find('dd', class_="lemmaWgt-lemmaTitle-title").find("h1") res_data['title'] = title_node.get_text() #
summary_node = soup.find('div', class_="lemma-summary") res_data['summary'] = summary_node.get_text() 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


5.url管理器  url_manager.py

#_*_coding:utf-8_*_

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

    #向管理器中添加新的url
    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)

    #向管理器中添加批量的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)

    #判断管理器中是否有新的url
    def has_new_url(self):
        return len(self.new_urls) != 0

    #获取新的带爬取的url
    def get_new_url(self):
        new_url = self.new_urls.pop()
        self.old_urls.add(new_url)
        return new_url





备注:

1.urljoin是拼接url地址的方法,比如 urljoin("http://www.asite.com/folder/currentpage.html""anotherpage.html") 会输出'http://www.asite.com/folder/anotherpage.html'

urljoin("http://www.asite.com/folder/currentpage.html""folder2/anotherpage.html")会输出'http://www.asite.com/folder/folder2/anotherpage.html'

urljoin("http://www.asite.com/folder/currentpage.html""/folder3/anotherpage.html") 会输出'http://www.asite.com/folder3/anotherpage.html' 

urljoin("http://www.asite.com/folder/currentpage.html""../finalpage.html")会输出'http://www.asite.com/finalpage.html' 


2.pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值


3.页面内容随时可能变化,根据不同情况做不同的分析处理,比如以前a标签的href跟现在的不一样,是类似于:/item/123.htm格式,所以在以前,页面解析器找a的代码为

# links = soup.find_all('a', href=re.compile(r"/item/\d+\.html"))



你可能感兴趣的:(python)