Python爬蟲實戰(4)_淘寶商品比價爬蟲

此篇筆記是筆者在學習嵩天老師的《Python網絡爬蟲與信息提取》課程及筆者實踐網絡爬蟲的筆記。

一、前提準備

1、功能描述

獲取淘寶搜索頁面的信息,提取其中的商品名稱和價格。

2、分析頁面

①先確定搜索url
1
根據上圖我們可以看到url爲:https://s.taobao.com/search?q後面的書包爲自定義搜索內容。
由此我們可以知道起始url爲:start_url = 'https://s.taobao.com/search?q=' + 自定義搜索內容
②確定每一頁物品的數量。
2
3
根據上面點擊不同頁面可以發現,每一頁的間距爲44
③每個商品的價格以及內容簡介:
4
5

3、代碼實現

步驟:
提交商品搜索請求,循環獲取頁面
對於每個頁面,提取商品名稱和價格信息對於每個頁面,提取商品名稱和價格信息
將信息輸出到屏幕上將信息輸出到屏幕上

大體框架:

import requests
import re
def getHTMLText(url):  # 獲得頁面函數
	pass
	
def parsePage(ilt, html):  # 解析獲得的頁面
    pass

def printGoodlist(ilt):  # 輸出結果信息到屏幕
    pass
    
def main():  # 主函數
    goods = '書包'
    depth = 3  # 下一頁深度
    start_url = 'https://s.taobao.com/search?q=' + goods
    indolist = []  # 輸出結果
    for i in range(depth):
        try:
            url = start_url + '&s=' + str(48 * i)
            html = getHTMLText(url)
            parsePage(indolist, html)
        except:
            continue
    printGoodlist(indolist)
    
main()

4、完整代碼:

# =============================================
# --*-- coding: utf-8 --*--
# @Time    : 2020-03-20
# @Author  : 李華鑫
# @CSDN    : https://blog.csdn.net/qq_16146103
# @FileName: taobao.py
# @Software: PyCharm
# =============================================

import requests
import re
def getHTMLText(url):  # 獲得頁面函數
    try:
        header = {
            'user-agent': 'Mozilla/5.0 ',
            'cookie': 'thw=cn; cna=npj6FSROsjACAdodv5gJhCng; hng=CN%7Czh-CN%7CCNY%7C156; tracknick=a459804692; _cc_=Vq8l%2BKCLiw%3D%3D; tg=0; enc=QBWbMOc0vQMNrTeNZMKkNSam6PhBuBNZFXZb7jRKj1R6%2FnZ%2FAztJW%2F4Ql%2BaqZxBArE4hIF2kV2dUg%2BBZSV88Eg%3D%3D; x=e%3D1%26p%3D*%26s%3D0%26c%3D0%26f%3D0%26g%3D0%26t%3D0%26__ll%3D-1%26_ato%3D0; miid=778994371391611536; t=c8d997f8c3862a9545d7aa8e0f55a811; _m_h5_tk=35adf942f203d5b2def2e96c38527acf_1579166355669; _m_h5_tk_enc=0f3e60d1c12cd628e261b932e21ab4a2; cookie2=15c929f24b3d18aec75687bbefabacb3; v=0; _tb_token_=e9b30e375eee7; alitrackid=www.taobao.com; lastalitrackid=www.taobao.com; __guid=154677242.3514116682747917000.1579155943921.0774; _uab_collina=157915745635971448621381; x5sec=7b227365617263686170703b32223a223365323561373037306538313737393931373032646330666464613337346335434b6154675045464549756a734e6e372f4a724f68674561444449314f5467344e5459344e6a55374d513d3d227d; JSESSIONID=391518D427C8B71F1754C4144A533BCA; monitor_count=8; isg=BE9PlXPQTWYkTEpDzc8TlxxO3uNZdKOWgEm-D2Fcj77tMG0yYUXr5h6mMmCOSHsO; l=cBa32tzuqwYH7YbhBOCwZuI8jO79hIRVguPRwnNXi_5dY18KvH_Oomns5eJ6cjWdtkLW4IFj7Ty9-etuiRHx3mx-g3fP.'
        }
        r = requests.get(url, headers=header, timeout=30)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        # print(r.text)
        return r.text
    except:
        return ""

def parsePage(ilt, html):  # 解析獲得的頁面
    try:
        plt = re.findall(r'\"view_price\"\:\"[\d\.]*"', html)
        tlt = re.findall(r'\"raw_title\"\:\".*?"', html)
        for i in range(len(plt)):
            price = eval(plt[i].split(':')[1])
            title = eval(tlt[i].split(':')[1])
            ilt.append([price, title])
    except:
        print("")

def printGoodlist(ilt):  # 輸出結果信息到屏幕
    tplt = "{:4}\t{:8}\t{:16}"
    print(tplt.format("序號", "價格", "商品名稱"))
    count = 0
    for g in ilt:
        count = count + 1
        print(tplt.format(count, g[0], g[1]))

def main():  # 主函數
    goods = '書包'
    depth = 3  # 下一頁深度
    start_url = 'https://s.taobao.com/search?q=' + goods
    indolist = []  # 輸出結果
    for i in range(depth):
        try:
            url = start_url + '&s=' + str(48 * i)
            html = getHTMLText(url)
            parsePage(indolist, html)
        except:
            continue
    printGoodlist(indolist)

main()

5、運行結果

6

6、總結

本爬蟲程序並沒有使用BS4,使用的是正則表達式,同時本程序也沒有使用存儲程序,這些都可以完善的,在此我就不完善了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章