7

Python实战 | 手拉手教你爬取贝壳房源数据

 2 years ago
source link: https://blog.csdn.net/G6_12/article/details/115893317
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.



随着人工智能的不断发展,机器学习这门技术也越来越重要,很多人都开启了学习机器学习,本文就介绍了机器学习的基础内容,了解python爬虫


一、爬虫是什么?

在进行大数据分析或者进行数据挖掘的时候,数据源可以从某些提供数据统计的网站获得,也可以从某些文献或内部资料中获得,但是这些获得数据的方式,有时很难满足我们对数据的需求,而手动从互联网中去寻找这些数据,则耗费的精力过大。此时就可以利用爬虫技术,自动地从互联网中获取我们感兴趣的数据内容,并将这些数据内容爬取回来,作为我们的数据源,从而进行更深层次的数据分析,并获得更多有价值的信息。 在使用爬虫前首先要了解爬虫所需的库(requests)或者( urllib.request ),该库是为了爬取数据任务而创建的。

二、使用步骤

1.引入库

代码如下(示例):

import os
import urllib.request
import random
import time
class BeikeSpider:
    def __init__(self, save_path="./beike"):
        """
        贝壳爬虫构造函数
        :param save_path: 网页保存目录
        """

2.读入数据

代码如下 :

# 网址模式
        self.url_mode = "http://{}.fang.ke.com/loupan/pg{}/"
        # 需爬取的城市
        self.cities = ["cd", "sh", "bj"]
        # 每个城市爬取的页数
        self.total_pages = 20
        # 让爬虫程序随机休眠5-10秒
        self.sleep = (5, 10)
        # 网页下载保存根目录
        self.save_path = save_path
        # 设置用户代理,是爬虫程序伪装成浏览器
        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"}
        ]

        # 创建保存目录
        if not os.path.exists(self.save_path):
            os.makedirs(self.save_path)
   def crawl(self):
        """
        执行爬取任务
        :return: None
        """

该处使用的url网络请求的数据。


3.随机选择一个ip地址构建代理服务器

        for city in self.cities:
            print("正在爬取的城市:", city)
            # 每个城市的网页用单独的目录存放
            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):
                # 构建完整的url
                url = self.url_mode.format(city, page)
                # 构建Request对象, 将url和请求头放入对象中
                request = urllib.request.Request(url, headers=self.headers)

                # 随机选择一个代理IP
                proxy = random.choice(self.proxies)
                # 构建代理服务器处理器
                proxy_handler = urllib.request.ProxyHandler(proxy)
                # 构建opener
                opener = urllib.request.build_opener(proxy_handler)
                # 使用构建的opener打开网页
                response = opener.open(request)
                html = response.read().decode("utf-8")
                # 网页保存文件名(包含路径)
                filename = os.path.join(path, str(page)+".html")

                # 保存网页
                self.save(html, filename)
                print("第%d页保存成功!" % page)

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

该处除随机选择ip地址以外还会限制爬取数据的速度,避免暴力爬取。


4.运行代码

    def save(self, html, filename):
        """
        保存下载的网页
        :param html: 网页内容
        :param filename: 保存的文件名
        :return:
        """

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

    def parse(self):
        """
        解析网页数据
        :return:
        """
        pass


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

在这里插入图片描述

运行结果就会这样,会保存在你的文件夹中。


这里对文章进行总结:今天分析这波代码目的是为了让大家清晰明亮的了解python爬虫的运作,和大家一起学习
以上就是今天要讲的内容,本文仅仅简单介绍了pandas的使用,而urllib.request提供了大量能使我们快速便捷地爬取数据。

小郭锅在此希望对你的编程之旅有所帮助,记得点赞关注哦
源代码文件已经放入资源里面需要的可以自行提取


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK