天天看點

python 讓挑選家具更友善

原文連結: https://mp.weixin.qq.com/s/tQ6uGBrxSLfJR4kk_GKB1Q

家中想置辦些家具,聽朋友介紹說蘇州蠡(li第二聲)口的家具比較出名,因為工作在蘇州,也去那邊看過,簡直...,走斷雙腿都逛不完,更何況還疲于逛街的。

也浏覽過家具城的官網,本着在一定的預算範圍之類挑選最合适的,作為一個程式猿,一顆不安分的心,決定自己爬蟲下網站,列出個excel表格,也友善給父母輩們檢視,順帶再練習下爬蟲的。

同樣後期實地再去購買時,也可以帶上這份表格進行參考。

關于爬蟲的文章還有另外兩篇實戰的:

python itchat 爬取微信好友資訊 python爬蟲學習:爬蟲QQ說說并生成詞雲圖,回憶滿滿

excel表格:

image

詞頻統計:

爬蟲分析

打開官網

http://www.likoujiaju.com/

,可以看到分類,這裡以「沙發」來舉例。

總共8頁的資料,第一頁的網址裡 sell/list-66.html,第二頁的sell/list-66-2.html,是以sell/list-66-1.html也就是第一頁資料了,這樣就更友善周遊網址來擷取資料了。

同時這裡使用

BeautifulSoup

解析資料,F12查找标題、價格、圖檔對應的标簽。

def get_data():
    # 定義一個清單存儲資料
    furniture = []
    # 用于存放家具名,後續用于生成詞頻
    title_all = ""
    # 分頁資料擷取
    for num in range(1, 9):
        url = "http://www.likoujiaju.com/sell/list-66-%d.html" % num
        response = requests.get(url)
        content = BeautifulSoup(response.content, "lxml")
        # 找到資料所在的div塊
        sm_offer = content.find("div", class_="sm-offer")
        lis = sm_offer.ul.find_all("li")
        # 周遊每一條資料
        for li in lis:
            # 價格
            price_span = li.find("span", class_="sm-offer-priceNum")
            price = price_span.get_text()
            # 名稱
            title_div = li.find("div", class_="sm-offer-title")
            title = title_div.a.get_text()
            title_all = title_all + title + " "
            # 圖檔
            photo_div = li.find("div", class_="sm-offer-photo")
            photo = photo_div.a.img.get("src")
            # 詳情連結
            href = photo_div.a.get("href")
            # 數組裡每一項是元祖
            furniture.append((price, title, photo, href))
    # 排序
    furniture.sort(key=take_price, reverse=True)
    # 生成excel
    create_excel(furniture, title_all)
           

爬取到的價格是string類型的,且有些價格并不明确的,是以這裡需要對價格進行處理并排序,用到的list的

sort(key=take_price)

方法,其中

key=take_price

指定的方法,使用指定的方法去進行比較排序。

# 傳參是清單的每一個元素,這裡即元祖
def take_price(enum):
    # 取元祖的第一個參數--價格,處理價格得到數值類型進行比較
    price = enum[0]
    if "面議" in price:  # 面議的話就設為0
        return 0
    start = price.index("¥")
    end = price.index("/")
    new_price = price[start + 1:end]
    return float(new_price)
           

再對清單進行排序操作,

reverse=True

降序排列

furniture.sort(key=take_price, reverse=True)
           

生成表格

這裡采用的

xlsxwriter

庫,便于圖檔的插入,安裝

pip install xlsxwriter

主要用到的方法:

xlsxwriter.Workbook("")

建立excel表格。

add_worksheet("")

建立工作表。

write(row, col, *args)

根據行、列坐标将資料寫入單元格。

set_row(row, height)

設定行高。

set_column(first_col, last_col, width)

設定列寬,

first_col

指定開始列位置,

last_col

指定結束列位置。

insert_image(row, col, image[, options])

用于插入圖檔到指定的單元格

建立兩個表,一個用于存放爬取的資料,一個用于存放詞頻。

# 建立excel
def create_excel(furniture, title_all):
    # 建立excel表格
    file = xlsxwriter.Workbook("furniture.xlsx")
    # 建立工作表1
    sheet1 = file.add_worksheet("sheet1")
    # 定義表頭
    headers = ["價格", "标題", "圖檔", "詳情連結"]
    # 寫表頭
    for i, header in enumerate(headers):
        # 第一行為表頭
        sheet1.write(0, i, header)
    # 設定列寬
    sheet1.set_column(0, 0, 24)
    sheet1.set_column(1, 1, 54)
    sheet1.set_column(2, 2, 34)
    sheet1.set_column(3, 3, 40)
    for row in range(len(furniture)):  # 行
        # 設定行高
        sheet1.set_row(row + 1, 180)
        for col in range(len(headers)):  # 列
            # col=2是目前列為圖檔,通過url去讀取圖檔展示
            if col == 2:
                url = furniture[row][col]
                image_data = BytesIO(urlopen(url).read())
                sheet1.insert_image(row + 1, 2, url, {"image_data": image_data})
            else:
                sheet1.write(row + 1, col, furniture[row][col])

    # 建立工作表2,用于存放詞頻
    sheet2 = file.add_worksheet("sheet2")
    # 生成詞頻
    word_count(title_all, sheet2)

    # 關閉表格
    file.close()
           

目錄下會生成 furniture.xlsx 表格

生成詞頻

利用jieba分詞對家具名進行分詞處理,用字典儲存各個名詞的數量,寫入到excel。

# 生成詞頻
def word_count(title_all, sheet):
    word_dict = {}
    # 結巴分詞
    word = jieba.cut(title_all)
    word_str = ",".join(word)
    # 處理掉特殊的字元
    new_word = re.sub("[ 【】-]", "", word_str)
    # 對字元串進行分割出清單
    word_list = new_word.split(",")
    for item in word_list:
        if item not in word_dict:
            word_dict[item] = 1
        else:
            word_dict[item] += 1
    # 對字典進行排序,按照數目排序
    val = sorted(word_dict.items(), key=lambda x: x[1], reverse=True)
    # 寫入excel
    for row in range(len(val)):
        for col in range(0, 2):
            sheet.write(row, col, val[row][col])

           

詞頻統計,實地去購買的時候,也可以根據相應的詞彙去咨詢賣家~

這篇文章用到的爬蟲方面的知識還是比較基礎的,excel表格的生成也是

xlsxwriter

庫的使用,制作成表格也友善父母輩檢視。當然,爬蟲的資料還可以用在許多地方。

詳細代碼見

github位址:

https://github.com/taixiang/furniture

歡迎關注我的部落格:

https://blog.manjiexiang.cn/

更多精彩歡迎關注微信号:春風十裡不如認識你

image.png

有個「佛系碼農圈」,歡迎大家加入暢聊,開心就好!

過期了,可加我微信 tx467220125 拉你入群。