1. 程式人生 > >爬取樓盤網並將資料儲存在excel表中

爬取樓盤網並將資料儲存在excel表中

初學,程式碼有點爛,有些錯誤先不處理。

#!/usr/bin/python
# -*- coding: <encoding name> -*-

import requests
from bs4 import BeautifulSoup
from openpyxl import Workbook



wb = Workbook()
ws = wb.active
ws.append(['序號','樓盤名稱', '面積', '價格','地址'])
# wb.save("e:sample.xlsx")


headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
}

# 定義樓盤的各項資訊列表,便於進行資料追加儲存
name_list = []
price_list = []
area_list = []
add_list = []

i = 1
pagenum = input('請輸入要抓取<樓盤網>多少頁的資料:')

# 通過迴圈,設定pagenum數值來抓取多少頁的樓盤資料
while i <= int(pagenum):
    url = 'http://fs.loupan.com/xinfang/p'+str(i)
    res = requests.get(url,headers = headers)
    print('第>>>>>  '+ str(i) + '  <<<<<頁資料抓取完畢!!' ) # 列印抓取頁面的程序
    res.encoding = res.apparent_encoding
    soup = BeautifulSoup(res.text,'html.parser')
    # 獲取樓盤名字,並追加儲存在name_list列表中
    name = soup.find_all('h3')
    for a in name:
        name_list.append(a.text)
    # 獲取樓盤面積大小,並追加儲存在area_list列表中
    area = soup.find_all(class_="type")
    for a in area:
        area_list.append(a.text)
    # 獲取樓盤地址,並追加儲存在add_list列表中
    add = soup.find_all(class_="add")
    for a in add:
        add_list.append(a.text)
    # 獲取樓盤價格,並追加儲存在price_list列表中
    price = soup.find_all('li',class_="price")
    for b in price:
        price_list.append(b.text)

    i += 1


x = 0
y = 27 # 每一頁有27個樓盤資訊需要爬取,進行for迴圈不要超出。並通過append一行一行將樓盤資訊儲存到Excel表格中
while x < y*(i-1):
    ws.append([str(x+1),name_list[x],area_list[x],price_list[x],add_list[x]])
    x += 1


wb.save("e:sample.xlsx") # 將檔案存檔