App下載

Python怎么爬取房源數(shù)據(jù)?爬蟲實戰(zhàn)!

猿友 2021-07-21 11:22:56 瀏覽數(shù) (2869)
反饋

許多小伙伴在學(xué)習(xí)爬蟲的時候缺少一些實際項目進行練手,今天小編帶來了一個python爬取房源數(shù)據(jù)的python爬蟲源代碼。接下來就讓我們來看一看怎么爬取房源數(shù)據(jù)吧。

一、爬蟲是什么?

 在進行大數(shù)據(jù)分析或者進行數(shù)據(jù)挖掘的時候,數(shù)據(jù)源可以從某些提供數(shù)據(jù)統(tǒng)計的網(wǎng)站獲得,也可以從某些文獻或內(nèi)部資料中獲得,但是這些獲得數(shù)據(jù)的方式,有時很難滿足我們對數(shù)據(jù)的需求,而手動從互聯(lián)網(wǎng)中去尋找這些數(shù)據(jù),則耗費的精力過大。此時就可以利用爬蟲技術(shù),自動地從互聯(lián)網(wǎng)中獲取我們感興趣的數(shù)據(jù)內(nèi)容,并將這些數(shù)據(jù)內(nèi)容爬取回來,作為我們的數(shù)據(jù)源,從而進行更深層次的數(shù)據(jù)分析,并獲得更多有價值的信息。 在使用爬蟲前首先要了解爬蟲所需的庫(requests)或者( urllib.request ),該庫是為了爬取數(shù)據(jù)任務(wù)而創(chuàng)建的。

 二、使用步驟

 本篇文章所有url皆為不可用url,不可直接運行!(爬取他人的數(shù)據(jù)是一種違法行為,學(xué)習(xí)爬蟲的時候請注意!)

1.引入庫

代碼如下(示例):

import os
import urllib.request
import random
import time
class BeikeSpider:
    def __init__(self, save_path="./beike"):
        """
        貝殼爬蟲構(gòu)造函數(shù)
        :param save_path: 網(wǎng)頁保存目錄
        """

2.讀入數(shù)據(jù)

代碼如下 :

# 網(wǎng)址模式
        self.url_mode = "http://{}.***.com/loupan/pg{}/"
        # 需爬取的城市
        self.cities = ["cd", "sh", "bj"]
        # 每個城市爬取的頁數(shù)
        self.total_pages = 20
        # 讓爬蟲程序隨機休眠5-10秒
        self.sleep = (5, 10)
        # 網(wǎng)頁下載保存根目錄
        self.save_path = save_path
        # 設(shè)置用戶代理,是爬蟲程序偽裝成瀏覽器
        self.headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36"}
        # 代理IP的信息
        self.proxies = [
            {"https": "123.163.67.50:8118"},
            {"https": "58.56.149.198:53281"},
            {"https": "14.115.186.161:8118"}
        ]

        # 創(chuàng)建保存目錄
        if not os.path.exists(self.save_path):
            os.makedirs(self.save_path)
   def crawl(self):
        """
        執(zhí)行爬取任務(wù)
        :return: None
        """

該處使用的url網(wǎng)絡(luò)請求的數(shù)據(jù)。

3.隨機選擇一個ip地址構(gòu)建代理服務(wù)器

 for city in self.cities:
            print("正在爬取的城市:", city)
            # 每個城市的網(wǎng)頁用單獨的目錄存放
            path = os.path.join(self.save_path, city)
            if not os.path.exists(path):
                os.makedirs(path)

            for page in range(1, self.total_pages+1):
                # 構(gòu)建完整的url
                url = self.url_mode.format(city, page)
                # 構(gòu)建Request對象, 將url和請求頭放入對象中
                request = urllib.request.Request(url, headers=self.headers)

                # 隨機選擇一個代理IP
                proxy = random.choice(self.proxies)
                # 構(gòu)建代理服務(wù)器處理器
                proxy_handler = urllib.request.ProxyHandler(proxy)
                # 構(gòu)建opener
                opener = urllib.request.build_opener(proxy_handler)
                # 使用構(gòu)建的opener打開網(wǎng)頁
                response = opener.open(request)
                html = response.read().decode("utf-8")
                # 網(wǎng)頁保存文件名(包含路徑)
                filename = os.path.join(path, str(page)+".html")

                # 保存網(wǎng)頁
                self.save(html, filename)
                print("第%d頁保存成功!" % page)

                # 隨機休眠
                sleep_time = random.randint(self.sleep[0], self.sleep[1])
                time.sleep(sleep_time)

該處除隨機選擇ip地址以外還會限制爬取數(shù)據(jù)的速度,避免暴力爬取。

4.運行代碼

def save(self, html, filename):
        """
        保存下載的網(wǎng)頁
        :param html: 網(wǎng)頁內(nèi)容
        :param filename: 保存的文件名
        :return:
        """

        f = open(filename, 'w', encoding="utf-8")
        f.write(html)
        f.close()

    def parse(self):
        """
        解析網(wǎng)頁數(shù)據(jù)
        :return:
        """
        pass

if __name__ == "__main__":
    spider = BeikeSpider()
    spider.crawl()


運行結(jié)果就會這樣,會保存在你的文件夾中。

總結(jié)

這里對文章進行總結(jié):今天分析這波代碼目的是為了讓大家清晰明亮的了解python爬蟲的運作,和大家一起學(xué)習(xí)
以上就是python爬取某房源數(shù)據(jù)的全部內(nèi)容,更多python爬蟲實戰(zhàn)案例請前往W3Cschool進行學(xué)習(xí)!



0 人點贊