【Python】【爬蟲】【爬狼】003_獲取搜索結果的頁數


獲取搜索內容的頁數

需要的包

import urllib.request  # 獲取網頁源碼
import re  # 正則表達式,進行文字匹配
from bs4 import BeautifulSoup  # 解析網頁

解析網頁

第一步,解析網頁為網頁源碼(【Python】【爬蟲系列】【爬狼】002_自定義獲取網頁源碼的函數 - 萌狼藍天 - 博客園 (cnblogs.com/mllt)

    # 獲取網頁源碼
    response_html = xrilang_UrlToDocument(Url)
    # xrilang_UrlToDocument是我自定義函數,如果你沒寫這個函數,直接使用,會報錯的。
    # 如果你想了解這個函數的具體內容,請看【爬狼系列】筆記第002篇

獲取搜索內容的頁數

分析網頁

image-20211215174707096

切換頁數,觀察地址欄變化。

根據觀察第二頁、第三頁鏈接如下

# 第二頁
https://www.yhdmp.cc/s_all?kw=love&pagesize=24&pageindex=1
# 第三頁
https://www.yhdmp.cc/s_all?kw=love&pagesize=24&pageindex=2

由此可以推測出,第一頁的地址為

https://www.yhdmp.cc/s_all?kw=love&pagesize=24&pageindex=0

s_all:Search All 搜索全部

kw:Key Word

pagesize:頁面大小(一頁有多少個視頻)

pageindex:頁面索引(索引從0開始,代表頁數。索引0是第一頁,索引1是第二頁,以此類推)

獲取視頻數量

image-20211215175653317

此處會顯示視頻數量,我們只需取出這個“數字”就可以了。

image-20211215175932817

方法1

	# 1.獲取所搜結果視頻數量
    reStr1 = r'''搜索結果, 共(.*?)個'''  # 正則規則
    # temp = re.findall(reStr1, response_html) # 在 response_html 中查找符合上述正則規則(reStr1)的內容
    # 運行結果為:['49']
    mvNumber = re.findall(reStr1, response_html)[0]  # 取出列表的第一項(索引為0) 設置變量mvNumber(搜索得到的視頻數量)
    # 運行結果為:49

方法2(推薦使用)

# 1.獲取所搜結果視頻數量
    reStr1 = re.compile(r'''搜索結果, 共(.*?)個''')  # 正則規則
    # temp = re.findall(reStr1, response_html) # 在 response_html 中查找符合上述正則規則(reStr1)的內容
    # 運行結果為:['49']
    mvNumber = re.findall(reStr1, response_html)[0]  # 取出列表的第一項(索引為0) 設置變量mvNumber(搜索得到的視頻數量)
    # 運行結果為:49

通過視頻數量獲取頁數

通過分析,我們知道,一頁有24個視頻,視頻總數在上面已經求出來了,那么會有多少頁呢,這就是一個小學的題了。

視頻總數/每頁展示視頻數=總頁數

即:視頻總數/24=總頁數

注意,如果有余數,則直接+1,結果為整數

 	# 通過視頻數量判斷有多少頁
    # pageNumber = int(mvNumber) / 24
    # 運行結果為:2.0416666666666665
    # 求出頁數
    if (int(mvNumber) % 24) == 0:
        pageNumber = int(mvNumber) / 24
    else:
        pageNumber = int(int(mvNumber) / 24) + 1
    # 最終得到頁數結果 pageNumber
    
    # mvNumber是視頻總數

將此功能編寫為函數

為了方便求頁數,我們需要將次功能編寫為函數方便我們使用

def xrilag_SearchAll(keyword):
    """
    '獲取搜索內容的總頁數'
    :param keyword:搜索的關鍵字
    :return:int 搜索結果的總頁數
    """
    # 基礎鏈接
    baseUrl = "https://www.yhdmp.cc/s_all?ex=1&kw="
    Url = baseUrl + keyword
    # 獲取網頁源碼
    response_html = xrilang_UrlToDocument(Url)
    # 1.獲取所搜結果視頻數量
    reStr1 = re.compile(r'''搜索結果, 共(.*?)個''')  # 正則規則
    # temp = re.findall(reStr1, response_html) # 在 response_html 中查找符合上述正則規則(reStr1)的內容
    # 運行結果為:['49']
    mvNumber = re.findall(reStr1, response_html)[0]  # 取出列表的第一項(索引為0) 設置變量mvNumber(搜索得到的視頻數量)
    # 運行結果為:49

    # 通過視頻數量判斷有多少頁
    # pageNumber = int(mvNumber) / 24
    # 運行結果為:2.0416666666666665
    # 求出頁數
    if (int(mvNumber) % 24) == 0:
        pageNumber = int(mvNumber) / 24
    else:
        pageNumber = int(int(mvNumber) / 24) + 1
    # 最終得到頁數結果 pageNumber
    return pageNumber

學習本文,最重要的是學習思維和處理方式


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM