[python]百度貼吧爬蟲

eg.

爬取西安交通大學吧內容,並以['url':page_url,'title':title,'para':reply]形式存儲到MongoDB數據庫。

一、相關信息介紹

爬蟲是一段自動抓取互聯網信息的程序。一般情況下采取人工方式從互聯網上獲取少量的信息,爬蟲可以從一個URL出發,訪問它所關聯的URL,並且從每個頁面中獲取有價值數據。


這是輕量級(無需登錄和異步加載的靜態網頁的抓取)網絡爬蟲的開發,採用python語言編寫,主要包括URL管理器、網頁下載器(urllib2)、網頁解析器(BeautifulSoup),實現百度貼吧網絡爬蟲相關的頁面數據,簡單爬蟲的架構如下:


簡單爬蟲架構流程如下:

二、程序按照架構分爲以下五個主要的py文件:

config.py  --  配置MongoDB相關信息

from pymongo import MongoClient

conn = MongoClient('127.0.0.1',27017)
db_crawl = conn.mydb_crawl    #連接mydb_test數據庫,沒有則自動創建
my_crawl = db_crawl.test_crawl    #使用test_set集合,沒有則自動創建


主調度文件爲TieBaCrawl.py

# coding:utf8
import html_parser
import url_manager

from Crawl import html_downloader


class SpiderMain(object):
    def __init__(self):
        self.urls = url_manager.UrlManager()
        self.downloader = html_downloader.HtnlDownloader()
        self.parser = html_parser.HtmlParser()

    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 = self.parser.parse(new_url, html_cont)
                self.urls.add_new_urls(new_urls)
                # if count == 100:
                #     break
                count = count + 1
            except:
                print ('craw failed')


if __name__ == "__main__":
    root_url = "http://tieba.baidu.com/f?kw=%E8%A5%BF%E5%AE%89%E4%BA%A4%E9%80%9A%E5%A4%A7%E5%AD%A6&traceid="
    obj_spider = SpiderMain()
    obj_spider.craw(root_url)


URL管理器 url_manager.py

# coding:utf8
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


html下載器 html_downloader.py

# coding:utf8
import urllib
from urllib import request
class HtnlDownloader(object):
    def download(self, url):
        if url is None:
            print("url is None")
            return None
        response = urllib.request.urlopen(url)
        if response.getcode() != 200:  # ==200網絡請求成功的意思,返回這個狀態表示已經獲取到數據了
            print("response.getcode():", response.getcode(),"!=200")
            return
        return response.read()


html解析器 html_parser.py

# coding:utf8
import re
from urllib import parse

from bs4 import BeautifulSoup

from Crawl.config import *


class HtmlParser(object):
    def _get_new_urls(self, page_url, soup):
        new_urls = set()
        links = soup.find_all('a',href=re.compile(r".*\/p\/.*"))     #匹配帖子的href
        for link in links:
            new_url = link['href']
            new_full_url = parse.urljoin(page_url, new_url)
            new_urls.add(new_full_url)
        return new_urls

    def _get_new_data(self, page_url, soup):

        str_ = []
        title_node = soup.find('title')#貼吧首頁每個帖子都是一個title,點進去每個帖子的title也有標識
        title = title_node.get_text()
        # print("title:",title)


        if soup.find('a',rel = r"noreferrer") is not None:
            para_node = soup.find_all('a', rel=r"noreferrer")
        else:
            para_node = soup.find_all('div',class_="d_post_content_main")
            # print(len(para_node))
            for node in para_node:
                try:
                    temp = node.get_text()
                    temp = str(temp).replace(" ","").replace("\n","")
                    if temp is not "":
                        if temp in title:     #不能獲取帖子裏二級及其以後的回覆內容
                            print(temp,"in title:",title,"跳過")
                        else:
                            str_.append(temp)
                except:
                    pass
        my_crawl.insert([{'url':page_url,'title':title,'para':str_}])    #將URL、title、para插入數據庫



    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)
        self._get_new_data(page_url,soup)
        return new_urls


三、運行結果存儲於MongoDB,RoBo 3T可視化顯示如下:


發佈了74 篇原創文章 · 獲贊 18 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章