某寶爬取

案例簡介

在這裏插入圖片描述
搜索的首頁鏈接
https://s.taobao.com/search?q=連衣裙&imgfile=&js=1&stats_click=search_radio_all%3A1&initiative_id=staobaoz_20200212&ie=utf8
第二頁鏈接
https://s.taobao.com/search?q=連衣裙&imgfile=&js=1&stats_click=search_radio_all%3A1&initiative_id=staobaoz_20200212&ie=utf8&bcoffset=3&ntoffset=3&p4ppushleft=1%2C48&s=44
第三頁
https://s.taobao.com/search?spm=a21bo.2017.201856-fline.1.5af911d9hm0jKA&q=%E8%BF%9E%E8%A1%A3%E8%A3%99&refpid=420460_1006&source=tbsy&style=grid&tab=all&pvid=d0f2ec2810bcec0d5a16d5283ce59f66&bcoffset=0&p4ppushleft=3%2C44&s=88

第二頁與第三頁的s= 不同正好表示的是商品數

在這裏插入圖片描述

實例編寫

查看頁面信息名稱和價格
在這裏插入圖片描述
任何商品的價格是由"view":“price"這一鍵字對確定
在這裏插入圖片描述
商品名稱前也有一個鍵
“raw_title”:”【商場同款】太平鳥女裝春裝2020新款娃娃領繡花連衣裙A1FAA1223"
即"raw_title":“名稱”

因此想獲得這兩個信息,只需要在獲得的文本中檢索到view_price,和raw_title,並把後續的信息提取出來即可
用正則表達式就十分合適
這個信息雖然在HTML頁面中,但它是一種腳本語言的體現,並不是一個完整的HTML頁面的表示

#功能描述
#目標:獲取淘寶搜索頁面信息,提取商品的名稱價格
#淘寶的搜索接口,翻頁的處理
#技術路線requests-re
# 步驟1:提交商品搜索請求,循環獲取頁面
# 步驟2:對於每個頁面,提取商品名稱和價格信息
# 步驟3:將信息輸出到屏幕上

import re
import requests
#獲得頁面
def getHTMLText(url):
    try:
        r=requests.get(url,timeout=30)
        r.raise_for_status()
        r.encoding=r.apparent_encoding
        return r.text
    except:
        return "WRONG!"


#對每一個獲得頁面進行解析,ilt-結果的列表類型,html-相關HTML頁面的信息
def parsePage(ilt,html):
    try:
        #  \表示引入一個"view_price",即首先檢索"view_price"字符串,並且獲取後面的\d.形成的相關信息
        # 通過這個獲得"view_price"和後面的價格,所有獲得的信息保存到plt列表中
        plt=re.findall(r'\"view_price\"\:\"[\d\.]*\"',html)
        # *?表示最小匹配
        tlt=re.findall(r'\"raw_title\"\:\".*?\"',html)
        for i in range(len(plt)):
            #使用eval()函數 除去雙引號單引號,split函數分割字符串獲得鍵字對的後半部分
            price=eval(plt[i].split(':')[1])
            title=eval(tlt[i].split(':')[1])
            #寫入列表中
            ilt.append([price,title])
    except:
        print("wrong")


#將商品信息輸出到屏幕上
def printGoodsList(ilt):
    #通過大括號定義槽函數
    #對第1個位置給定長度爲4,第2個位置給定長度爲8,第3個位置給定長度爲16
    tplt="{:4}\t{:8}\t{:16}"
    #打印輸出信息的表頭
    print(tplt.format("序號","價格","商品名稱"))
    #定義計數器count
    count=0
    for g in ilt:
        count=count+1
        print(tplt.format(count,g[0],g[1]))
def main():
    goods="%E8%BF%9E%E8%A1%A3%E8%A3%99"
    #爬取深度
    depth=2
    #通過和goods整合實現對商品的檢索
    start_url="https://s.taobao.com/search?q="+goods
    #對輸出結果定義變量infoList
    infoList=[]
    for i in range(depth):
        try:
            url=start_url+'&s='+str(44*i)
            html=getHTMLText(url)
            parsePage(infoList,html)
        except:
            continue
    printGoodsList(infoList)


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