首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >教你用python制作一个爬虫软件,城市二手房信息一览无余。。(附源码)

教你用python制作一个爬虫软件,城市二手房信息一览无余。。(附源码)

作者头像
Java架构师必看
发布2021-07-19 15:51:17
发布2021-07-19 15:51:17
1.3K0
举报
文章被收录于专栏:Java架构师必看Java架构师必看

教你用python制作一个爬虫软件,城市二手房信息一览无余。。(附源码)

强烈推介IDEA2020.2破解激活,IntelliJ IDEA 注册码,2020.2 IDEA 激活码

教你用python制作一个爬虫软件,城市二手房信息一览无余。。(附源码)

近年来随着我国二手房市场的逐渐放开,进入市场的二手房数量不断增加,二手房交易规模不断扩大,市场规模也在不断增长。数据显示,截至2018年末,我国累计二手房交易金额已经超过30万亿元;2019年我国二手房市场规模6.7万亿元,预计到2021年将达到8.4万亿元。 众所周知,发展二手房市场对于稳定住房价格,引导梯次消费,实现住房市场的健康发展具有重要的现实意义。但不可否认,二手房市场有效房源依旧供不应求,整体供求比例仅维持在1:4左右。如今,由于城市的扩张,新楼房通常只能建于远离城市中心之地,交通便利性较差,远不如建于城市中心地带的二手房。 对于二手房信息,我们也要多了解

软件展示

输入城市拼音的首字母,以及爬取的页数即可

20210605_235436

开发工具

python pycharm tkinter库(python内置库) parsel库

爬虫思路:

1.打开网址(采用链家网长沙二手房的网址) https://cs.lianjia.com/ershoufang/pg1/ 2.观察url变化,点击第二页,第三页 https://cs.lianjia.com/ershoufang/pg2/ https://cs.lianjia.com/ershoufang/pg3/ 3.观察网址是什么加载方式

可以确定为同步加载

4.打开北京链家二手房信息,记录url地址,观察url地址的变化 https://bj.lianjia.com/ershoufang/ 可以看出bj为北京首字母 5.开始写爬虫代码 解析获取文本内容 1、导包 2、变成CSS选择器对象 由于获取的内容都在ul标签下的li标签 变成CSS选择器对象,下图详解

代码语言:javascript
复制
        for page in range(1, pass_wd+1):
            start_url = f'https://{
     user_name}.lianjia.com/ershoufang/pg{
     page}/'
            headers = {
   
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 '
                              '(KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'
            }
            response = requests.get(start_url, headers=headers).content.decode()
            # pprint(response)
            selector = parsel.Selector(response)
            # 解析获取文本内容 1、导包 2、变成CSS选择器对象
            lis = selector.css('.sellListContent li')
            # self.text1.insert('insert', lis)
            dit = {
   }
            for li in lis:
                title = li.css('.title a::text').get()
                dit['标题'] = title
                positionInfo = li.css('.positionInfo a::text').getall()
                info = '-'.join(positionInfo)
                dit['开发商'] = info
                houseInfo = li.css('.houseInfo::text').get()
                dit['房子信息'] = houseInfo
                followInfo = li.css('.followInfo::text').get()
                dit['发布周期'] = followInfo
                Price = li.css('.totalPrice span::text').get()
                dit['售价/万'] = Price
                unitPrice = li.css('.unitPrice span::text').get()
                dit['单价'] = unitPrice

定义可视化窗口,并设置窗口和主题大小布局

代码语言:javascript
复制
    def __init__(self):
        """定义可视化窗口,并设置窗口和主题大小布局"""
        self.window = tk.Tk()
        self.window.title('城市二手房数据采集')
        self.window.geometry('800x600')

        """创建label_user按钮,与说明书"""
        self.label_user = tk.Label(self.window, text='要爬取的城市首字母:', font=('Arial', 12), width=30, height=2)
        self.label_user.pack()
        """创建label_user关联输入"""
        self.entry_user = tk.Entry(self.window, show=None, font=('Arial', 14))
        self.entry_user.pack(after=self.label_user)

        """创建label_passwd按钮,与说明书"""
        self.label_passwd = tk.Label(self.window, text="爬取多少页:(小于100)", font=('Arial', 12), width=30, height=2)
        self.label_passwd.pack()
        """创建label_passwd关联输入"""
        self.entry_passwd = tk.Entry(self.window, show=None, font=('Arial', 14))
        self.entry_passwd.pack(after=self.label_passwd)

        """创建Text富文本框,用于按钮操作结果的展示"""
        self.text1 = tk.Text(self.window, font=('Arial', 12), width=85, height=22)
        self.text1.pack()

        """定义按钮1,绑定触发事件方法"""
        self.button_1 = tk.Button(self.window, text='爬取', font=('Arial', 12), width=10, height=1,
                                  command=self.parse_hit_click_1)
        self.button_1.pack(before=self.text1)

        """定义按钮2,绑定触发事件方法"""
        self.button_2 = tk.Button(self.window, text='清除', font=('Arial', 12), width=10, height=1, command=self.parse_hit_click_2)
        self.button_2.pack(anchor="e")

代码注释很详细,这里不过多介绍, 注意:定义按钮,要绑定触发事件方法,command

创建窗口居中函数方法

代码语言:javascript
复制
    def center(self):
        """创建窗口居中函数方法"""
        ws = self.window.winfo_screenwidth()
        hs = self.window.winfo_screenheight()
        x = int((ws / 2) - (800 / 2))
        y = int((hs / 2) - (600 / 2))
        self.window.geometry('{}x{}+{}+{}'.format(800, 600, x, y))

定义触发事件2,删除文本框中内容

代码语言:javascript
复制
    def parse_hit_click_2(self):
        """定义触发事件2,删除文本框中内容"""
        self.entry_user.delete(0, "end")
        self.entry_passwd.delete(0, "end")
        self.text1.delete("1.0", "end")

源码展示:

代码语言:javascript
复制
import tkinter as tk
import requests, parsel
from pprint import pprint


class TKSpider(object):

    def __init__(self):
        """定义可视化窗口,并设置窗口和主题大小布局"""
        self.window = tk.Tk()
        self.window.title('城市二手房数据采集')
        self.window.geometry('800x600')

        """创建label_user按钮,与说明书"""
        self.label_user = tk.Label(self.window, text='要爬取的城市首字母:', font=('Arial', 12), width=30, height=2)
        self.label_user.pack()
        """创建label_user关联输入"""
        self.entry_user = tk.Entry(self.window, show=None, font=('Arial', 14))
        self.entry_user.pack(after=self.label_user)

        """创建label_passwd按钮,与说明书"""
        self.label_passwd = tk.Label(self.window, text="爬取多少页:(小于100)", font=('Arial', 12), width=30, height=2)
        self.label_passwd.pack()
        """创建label_passwd关联输入"""
        self.entry_passwd = tk.Entry(self.window, show=None, font=('Arial', 14))
        self.entry_passwd.pack(after=self.label_passwd)

        """创建Text富文本框,用于按钮操作结果的展示"""
        self.text1 = tk.Text(self.window, font=('Arial', 12), width=85, height=22)
        self.text1.pack()

        """定义按钮1,绑定触发事件方法"""
        """即登录按钮,当点击时将执行parse_hit_click_1方法。在真实使用场景中"""
        """parse_hit_click_1中可替换为自己写的真正登录函数。这里仅为示例"""
        self.button_1 = tk.Button(self.window, text='爬取', font=('Arial', 12), width=10, height=1,
                                  command=self.parse_hit_click_1)
        self.button_1.pack(before=self.text1)

        """定义按钮2,绑定触发事件方法"""
        self.button_2 = tk.Button(self.window, text='清除', font=('Arial', 12), width=10, height=1, command=self.parse_hit_click_2)
        self.button_2.pack(anchor="e")

    def parse_hit_click_1(self):
        """定义触发事件1,调用main函数"""
        user_name = self.entry_user.get()
        pass_wd = int(self.entry_passwd.get())
        self.main(user_name, pass_wd)

    def main(self, user_name, pass_wd):
        """爬虫函数"""
        # 抓取每页的url
        for page in range(1, pass_wd+1):
            start_url = f'https://{
     user_name}.lianjia.com/ershoufang/pg{
     page}/'
            headers = {
   
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 '
                              '(KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'
            }
            response = requests.get(start_url, headers=headers).content.decode()
            # pprint(response)
            selector = parsel.Selector(response)
            # 解析获取文本内容 1、导包 2、变成CSS选择器对象
            lis = selector.css('.sellListContent li')
            # self.text1.insert('insert', lis)
            dit = {
   }
            for li in lis:
                title = li.css('.title a::text').get()
                dit['标题'] = title
                positionInfo = li.css('.positionInfo a::text').getall()
                info = '-'.join(positionInfo)
                dit['开发商'] = info
                houseInfo = li.css('.houseInfo::text').get()
                dit['房子信息'] = houseInfo
                followInfo = li.css('.followInfo::text').get()
                dit['发布周期'] = followInfo
                Price = li.css('.totalPrice span::text').get()
                dit['售价/万'] = Price
                unitPrice = li.css('.unitPrice span::text').get()
                dit['单价'] = unitPrice
                """爬取的内容展示在文本框中"""
                self.text1.insert("insert", dit)
                self.text1.insert("insert", '\n ')      # 添加换行,好观察一点
                self.text1.insert("insert", '\n ')
            printinfo = print(f'*********第{
     page}页打印完成*********')


    def parse_hit_click_2(self):
        """定义触发事件2,删除文本框中内容"""
        self.entry_user.delete(0, "end")
        self.entry_passwd.delete(0, "end")
        self.text1.delete("1.0", "end")

    def center(self):
        """创建窗口居中函数方法"""
        ws = self.window.winfo_screenwidth()
        hs = self.window.winfo_screenheight()
        x = int((ws / 2) - (800 / 2))
        y = int((hs / 2) - (600 / 2))
        self.window.geometry('{}x{}+{}+{}'.format(800, 600, x, y))

    def run_loop(self):
        """禁止修改窗体大小规格"""
        self.window.resizable(False, False)
        """窗口居中"""
        self.center()
        """窗口维持--持久化"""
        self.window.mainloop()


if __name__ == '__main__':
    t = TKSpider()
    t.run_loop()

代码写完之后打包一下 命令行输入pyinstaller -F 文件.py

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 教你用python制作一个爬虫软件,城市二手房信息一览无余。。(附源码)
    • 软件展示
      • 开发工具
      • 爬虫思路:
      • 定义可视化窗口,并设置窗口和主题大小布局
      • 创建窗口居中函数方法
      • 定义触发事件2,删除文本框中内容
    • 源码展示:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档