外行學(xué) Python 爬蟲 第八篇 功能優(yōu)化

在前一篇中講了如何開啟多線程來加快爬蟲的爬取速度,本節(jié)主要對爬蟲爬取內(nèi)容機(jī)型優(yōu)化,將生產(chǎn)商信息單獨獨立出來作為一張數(shù)據(jù)庫表,不再僅僅是存儲一個生產(chǎn)商的名稱,同時保存了生產(chǎn)商的網(wǎng)址和介紹。

解析生產(chǎn)商信息

針對生產(chǎn)商頁面的信息的解析方法請參考 外行學(xué) Python 爬蟲 第三篇 內(nèi)容解析,在這里我們只需要按照相同的方法解析出生產(chǎn)商名稱、網(wǎng)址、簡介等信息即可,生產(chǎn)商數(shù)據(jù)表內(nèi)容如下:

class Brands(Base, CRUDMixin):
    __tablename__ = 'brands'

    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(100), nullable=False, unique=True)
    url = Column(String(100))
    desc = Column(Text)

    materials = relationship('Materials', backref='brands')

在完成數(shù)據(jù)表和網(wǎng)頁信息解析相關(guān)的內(nèi)容后,我們需要將生產(chǎn)商頁面的 url 加入爬蟲的有效 url 中,在整個程序中使用正則表達(dá)式來判斷一個 url 是否是一個有效的 url,正則表達(dá)式的規(guī)則如下:

r'https?://(www|list|item).szlcsc.com(/(catalog|brand))?(/[0-9]*)?.html'

在 python 使用 re 模塊來處理正則表達(dá)式

該表達(dá)式可以過濾出一下網(wǎng)址:

'https://www.szlcsc.com/catalog.html'
'https://list.szlcsc.com/catalog/542.html'
'https://item.szlcsc.com/22931.html'
'https://www.szlcsc.com/brand.html'
'https://list.szlcsc.com/brand/11442.html'

以上網(wǎng)址包含了元件目錄、元件列表、元件詳情、生產(chǎn)商列表、生產(chǎn)商詳情等頁面。

一下 url 校驗的函數(shù),函數(shù)接收正則表達(dá)式和 url 兩個參數(shù)

    def check_url(self, regex, url):
        if regex is None or url is None:
            return False
        if re.match(regex, url) is None:
            return False
        return True

由于元件信息和生產(chǎn)商信息相互關(guān)聯(lián),且一個生產(chǎn)商可以對應(yīng)多個元件,因此需要先獲取生產(chǎn)商的信息,在獲取網(wǎng)頁中的 url 時,需要先對生產(chǎn)商的 url 進(jìn)行識別,然后在識別元件的 url,相關(guān)的函數(shù)如下:

    def __find_url(self, current_url, html):
        for link in html.find_all(name='a', href=re.compile(REGEX_EXP_BRAND_LIST)):
            url = link.get('href')
            if not self.url_in_bloomfilter(url):
                if Crawler.url_queue.qsize() < Crawler.max_url_count:
                    self.url_add_bloomfilter(url)
                    Crawler.url_queue.put(url)

        if self.check_url(REGEX_EXP_CATLOG_LIST, current_url):
            if Crawler.url_queue.qsize() > Crawler.max_url_count:
                Crawler.url_queue.put(current_url)
            else:
                self.get_product_item_url(current_url)

        for link in html.find_all(name='a', href=re.compile(REGEX_EXP_ALL)):
            url = link.get('href')
            if not self.url_in_bloomfilter(url):
                if Crawler.url_queue.qsize() < Crawler.max_url_count:
                    self.url_add_bloomfilter(url)
                    Crawler.url_queue.put(url)

整個程序的執(zhí)行流程

image

真?zhèn)€程序執(zhí)行后,在數(shù)據(jù)庫中可以看到生產(chǎn)商、元件信息、元件價格等三張數(shù)據(jù)表,后面可以對著三個表的數(shù)據(jù)進(jìn)行分析。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容