首页 > 编程语言 >Python爬虫案例:从某居网爬取房源信息

Python爬虫案例:从某居网爬取房源信息

时间:2024-06-16 11:29:29浏览次数:12  
标签:property Python section 某居网 find content div 爬虫 class

网站链接:sjz.anjuke.com

目标数据:位置、面积、价格、房源链接

约束条件:房产价格在80-140w

首先在浏览器上输入网址,通过鼠标右键-“检查”来确定各网页元素在html源代码中的位置和构成

通过检查导航的价格索引,找出了80-140w的房源信息的网页链接,url依次以13-15结尾并且其它数据保持一致 

进入其中一个价格区间的网页,观察到目标数据在一个 tongji_tag=fcpc_ersflist_gzcount、class=property的div标签中且网页存在若干分页

掌握了目标网页的构成之后就可以开始编写对应的程序了

首先引入需要的python模块并且初始化一些数据,占位符“%d”代表不同网页变化的特征序号

import requests
from bs4 import BeautifulSoup
url = "https://sjz.anjuke.com/sale/m172%d-p%d/"
head = {'User-Agent': ''}  # 字典的值从标头获取

然后根据目标网页构建相应范围的循环,我们的目标网站url尾数从13-15且每个价格区间的网站有不知数目的若干分页,在遍历分页时用while循环和try语句以便在分页结束时跳出循环

for i in range(13, 16):
    num = 1
    while True:
        try:
           '''以下是获取数据的逻辑'''

           '''代码结束'''
        except Exception as e:
            print(e)
            break
        num += 1

之后编写爬取房源价格、面积、地点、对应链接的逻辑:首先通过填充占位符得到正确的url 并解析,通过find、find_all语句获取包含目标数据的所有大标签并存入一个元组,遍历该元组并获取每一个大标签的目标数据(在遇到class、id相同的兄弟标签时用.contents方法获取其父母的所有儿子再用索引获取目标标签)

html = requests.get(url % (i, num), headers=head).text
soup = BeautifulSoup(html, 'html.parser')
arr = (soup.find('div', id='__nuxt').find('div', id='__layout').find('div', id='esfMain').find('section',class_='list-body').find('section', class_='list-main').find('section', class_='list-left').find('section',class_='list').findAll('div',class_='property'))
for item in arr:
    link=item.find('a')['href']
    price=item.find('div',class_='property-content').find('div',class_='property-price').find('p',class_='property-price-total').find('span',class_='property-price-total-num').get_text(strip=True)
    area=item.find('div',class_='property-content').find('div',class_='property-content-detail').find('section').find('div',class_='property-content-info').contents[2].get_text(strip=True)
    pos=item.find('div',class_='property-content').find('div',class_='property-content-detail').find('section').find('div',class_='property-content-info property-content-info-comm').get_text(strip=True)

最后将数据存入txt文件即可

 message=str(count)+"、"+"价格:"+str(price)+"万"+" "+"面积:"+str(area)+" "+"地址:"+str(pos)+" "+str(link)
                with open("D:/hourse.txt", "a") as f:#填存储文件的地址
                    f.write(message)
                    f.close()

 

 注意再爬取过程中出现nonetype object has no attribute "find"可能是爬取次数过多网站跳出了图形验证码或者是写代码时粗心填错了find中的参数,网站跳出验证码时手动填写验证码即可或者少量多次获取数据来应对反爬机制

完整代码

import requests
from bs4 import BeautifulSoup
url = "https://sjz.anjuke.com/sale/m172%d-p%d/"
head = {'User-Agent': ''}  # 字典的值从标头获取
count=1
for i in range(13, 16):
    num = 1
    while True:
        try:
            html = requests.get(url % (i, num), headers=head).text
            soup = BeautifulSoup(html, 'html.parser')
            arr = (soup.find('div', id='__nuxt').find('div', id='__layout').find('div', id='esfMain').find('section',class_='list-body').find('section', class_='list-main').find('section', class_='list-left').find('section',class_='list').findAll('div',class_='property'))
            for item in arr:
                link=item.find('a')['href']
                price=item.find('div',class_='property-content').find('div',class_='property-price').find('p',class_='property-price-total').find('span',class_='property-price-total-num').get_text(strip=True)
                area=item.find('div',class_='property-content').find('div',class_='property-content-detail').find('section').find('div',class_='property-content-info').contents[2].get_text(strip=True)
                pos=item.find('div',class_='property-content').find('div',class_='property-content-detail').find('section').find('div',class_='property-content-info property-content-info-comm').get_text(strip=True)
                message=str(count)+"、"+"价格:"+str(price)+"万"+" "+"面积:"+str(area)+" "+"地址:"+str(pos)+" "+str(link)
                with open("", "a") as f:#填自己的存储地址
                    f.write(message)
                    f.close()
        except Exception as e:
            print(e)
            break
        num += 1

标签:property,Python,section,某居网,find,content,div,爬虫,class
From: https://blog.csdn.net/2301_76152811/article/details/139697759

相关文章

  • 批量异步上传aws图片脚本(python)
    背景工作中需要上传一些测试图片,于是网上找找资料(官方说明),前置步骤如下。python需要3.8以上,安装最新的boto3库:pipinstallboto3有一个S3权限的aws账户,得到访问密钥ACCESS_KEY与SECRET_KEY,以及上传图片的存储桶位置安装异步编程asyncio,aiohttp库,方便本地异步上传图片代码......
  • python学习 - 对目录操作和对文件操作的 实例代码
    #!/usr/bin/python#-*-coding:UTF-8-*-importosimportos,shutilclassOperatingFile:defcreatFile(self,path):f=file(path,"w+")f.close()defreadFile(self,path):#方法一f=open("E:/aa......
  • python学习 - for循环 各种使用技巧 案例代码
    #!/usr/bin/python#-*-coding:UTF-8-*-forletterin'Python':#第一个实例print'当前字母:',letterfruits=['banana','apple','mango']forfruitinfruits:#第二个实例print'当前水果:',fr......
  • python学习 - 对list列表的操作 实例代码
    #!/usr/bin/evnpython#-*-encoding:utf-8-*-list=[1,4,3,3,"A","B","c","A"]#增加list.append("AA")#像末尾增加一个新元素list.insert(1,"B")#像指定索引位置插入元素list.extend(["D","DD"])#新......
  • python学习 - 读取xls文件的操作案例代码
    #!/usr/bin/evnpython#-*-encoding:utf-8-*-importxlrdimportxlwtimportxlutils.copyclassExcels:defcreateExcel(self):workbook=xlwt.Workbook()sheet=workbook.add_sheet(u"sheet页名称",cell_overwrite_ok=True)......
  • python学习 - 操作redis数据库常用指令 案例
    #-*-coding:UTF-8-*-importredisimporttimeclassTestRedis:def__init__(self):self.dbconn=NonedefopenRedis(self):#连接redis,加上decode_responses=True,写入的键值对中的value为str类型,不加这个参数写入的则为字节类型。......
  • 怎么把Python脚本打包成可执行程序exe文件?
    需求分析最近根据用户提的需求用python做了一个小工具,但是在给客户使用的时候不能直接发送python文件,毕竟让客户去安装python环境,那就离了大谱了。所以这时候就需要把多个py文件带着运行环境打包成EXE可执行文件。技术实现这里以window为例,Mac是同样的道理。一、检测脚......
  • python入门级经典交互式小程序
    今天学习做一个简单的交互式小程序知识点:1.对空列表进行添加元素,并分别打印每次添加的元素2.给while设置参数法进行循环3.for循环结合range()进行循环代码如下:klist=[]name=input("请输入你喜欢的明星:")while(name):  klist.append(name)  name=input......
  • 2024华为OD机试真题-堆内存申请-(C++/Python)-C卷D卷-100分
    2024华为OD机试题库-(C卷+D卷)-(JAVA、Python、C++)题目描述有一个总空间为100字节的堆,现要从中新申请一块内存,内存分配原则为:优先紧接着前一块已使用内存,分配空间足够且最接近申请大小的空闲内存。输入描述第1行是1个整数,表示期望申请的内存字节数第2到第N行是用空格......
  • 2024华为OD机试真题-围棋的气-(C++/Python)-C卷D卷-100分
     2024华为OD机试题库-(C卷+D卷)-(JAVA、Python、C++) 题目描述围棋棋盘由纵横各19条线垂直相交组成,棋盘上一共19x19=361个交点,对弈双方一方执白棋,一方执黑棋,落子时只能将棋子置于交点上。“气”是围棋中很重要的一个概念,某个棋子有几口气,是指其上下左右方向四个相......