一、前言、
????????在數據分析和挖掘領域中,網絡爬蟲是一種常見的工具,用于從網頁上收集數據。本文將介紹如何使用 Python 編寫簡單的網絡爬蟲程序,從鏈家網上海二手房頁面獲取房屋信息,并將數據保存到 Excel 文件中。
二、效果圖:
-
導入需要的庫:
requests
:用于發送 HTTP 請求和獲取網頁內容。BeautifulSoup
:用于解析 HTML 內容,提取所需信息。pandas
:用于數據處理和保存數據到 Excel 文件。
import requestsfrom bs4 import BeautifulSoupimport pandas as pd
???? 如果出現模塊報錯
??????? 進入控制臺輸入:建議使用國內鏡像源
pip install 模塊名稱 -i https://mirrors.aliyun.com/pypi/simple
???????? 我大致羅列了以下幾種國內鏡像源:
清華大學
https://pypi.tuna.tsinghua.edu.cn/simple阿里云
https://mirrors.aliyun.com/pypi/simple/豆瓣
https://pypi.douban.com/simple/ 百度云
https://mirror.baidu.com/pypi/simple/中科大
https://pypi.mirrors.ustc.edu.cn/simple/華為云
https://mirrors.huaweicloud.com/repository/pypi/simple/騰訊云
https://mirrors.cloud.tencent.com/pypi/simple/
三、代碼分析
????????首先,我們定義了一個函數 fetch_data(page_number)
,用于獲取指定頁面的房屋信息數據。這個函數會構建對應頁數的 URL,并發送 GET 請求獲取頁面內容。然后,使用 BeautifulSoup 解析頁面內容,并提取每個房屋信息的相關數據,如區域、房型、關注人數、單價和總價。最終將提取的數據以字典形式存儲在列表中,并返回該列表。
????????接下來,我們定義了主函數 main()
,該函數控制整個爬取和保存數據的流程。在主函數中,我們循環爬取前 10 頁的數據,調用 fetch_data(page_number)
函數獲取每一頁的數據,并將數據追加到列表中。然后,將所有爬取的數據存儲在 DataFrame 中,并使用 df.to_excel('lianjia_data.xlsx', index=False)
將數據保存到 Excel 文件中。
最后,在程序的入口處,通過 if __name__ == "__main__":
來執行主函數 main()
。
四、詳解代碼
-
定義
fetch_data(page_number)
函數:- 這個函數接收一個參數
page_number
,表示要爬取的頁面頁數。 - 構建相應頁數的 URL,并發送 GET 請求獲取頁面內容。
- 使用 BeautifulSoup 解析頁面內容,并提取每個房屋信息的相關數據,如區域、房型、關注人數、單價和總價。
- 將提取的數據以字典形式存儲在
rows
列表中,并返回該列表。
- 這個函數接收一個參數
# 收集單頁數據 xpanx.comdef fetch_data(page_number):url = f"https://sh.lianjia.com/ershoufang/pg{page_number}/"response = requests.get(url)if response.status_code != 200:print("請求失敗")return []soup = BeautifulSoup(response.text, 'html.parser')rows = []for house_info in soup.find_all("li", {"class": "clear LOGVIEWDATA LOGCLICKDATA"}):row = {}# 使用您提供的類名來獲取數據 xpanx.comrow['區域'] = house_info.find("div", {"class": "positionInfo"}).get_text() if house_info.find("div", {"class": "positionInfo"}) else Nonerow['房型'] = house_info.find("div", {"class": "houseInfo"}).get_text() if house_info.find("div", {"class": "houseInfo"}) else Nonerow['關注'] = house_info.find("div", {"class": "followInfo"}).get_text() if house_info.find("div", {"class": "followInfo"}) else Nonerow['單價'] = house_info.find("div", {"class": "unitPrice"}).get_text() if house_info.find("div", {"class": "unitPrice"}) else Nonerow['總價'] = house_info.find("div", {"class": "priceInfo"}).get_text() if house_info.find("div", {"class": "priceInfo"}) else Nonerows.append(row)return rows# 主函數def main():all_data = []for i in range(1, 11): # 爬取前10頁數據作為示例print(f"正在爬取第{i}頁...")all_data += fetch_data(i)# 保存數據到Excel xpanx.comdf = pd.DataFrame(all_data)df.to_excel('lianjia_data.xlsx', index=False)print("數據已保存到 'lianjia_data.xlsx'")
-
定義
main()
函數:- 在主函數中循環爬取前 10 頁的數據,調用
fetch_data(page_number)
函數獲取每一頁的數據,并將數據追加到all_data
列表中。 - 將所有爬取的數據存儲在 DataFrame 中。
- 最后使用
df.to_excel('lianjia_data.xlsx', index=False)
將數據保存到名為lianjia_data.xlsx
的 Excel 文件中。
- 在主函數中循環爬取前 10 頁的數據,調用
???????
五、完整代碼
?這段代碼的主要流程是通過循環遍歷頁面頁數,調用 fetch_data(page_number)
函數爬取每一頁的數據,并將數據保存到 Excel 文件中。整體上,這個程序完成了以下幾個主要功能:
- 發送 HTTP 請求并獲取網頁內容。
- 使用 BeautifulSoup 解析 HTML 內容,提取所需信息。
- 將提取的數據存儲在列表中。
- 將列表數據轉換為 DataFrame。
- 將 DataFrame 數據保存到 Excel 文件中。
import requestsfrom bs4 import BeautifulSoupimport pandas as pd# 收集單頁數據 xpanx.comdef fetch_data(page_number):url = f"https://sh.lianjia.com/ershoufang/pg{page_number}/"response = requests.get(url)if response.status_code != 200:print("請求失敗")return []soup = BeautifulSoup(response.text, 'html.parser')rows = []for house_info in soup.find_all("li", {"class": "clear LOGVIEWDATA LOGCLICKDATA"}):row = {}# 使用您提供的類名來獲取數據 xpanx.comrow['區域'] = house_info.find("div", {"class": "positionInfo"}).get_text() if house_info.find("div", {"class": "positionInfo"}) else Nonerow['房型'] = house_info.find("div", {"class": "houseInfo"}).get_text() if house_info.find("div", {"class": "houseInfo"}) else Nonerow['關注'] = house_info.find("div", {"class": "followInfo"}).get_text() if house_info.find("div", {"class": "followInfo"}) else Nonerow['單價'] = house_info.find("div", {"class": "unitPrice"}).get_text() if house_info.find("div", {"class": "unitPrice"}) else Nonerow['總價'] = house_info.find("div", {"class": "priceInfo"}).get_text() if house_info.find("div", {"class": "priceInfo"}) else Nonerows.append(row)return rows# 主函數def main():all_data = []for i in range(1, 11): # 爬取前10頁數據作為示例print(f"正在爬取第{i}頁...")all_data += fetch_data(i)# 保存數據到Excel xpanx.comdf = pd.DataFrame(all_data)df.to_excel('lianjia_data.xlsx', index=False)print("數據已保存到 'lianjia_data.xlsx'")if __name__ == "__main__":main()