利用python爬取贝壳网租房信息

前言

本文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理。

PS:如有需要Python学习资料的小伙伴可以加点击下方链接自行获取
python免费学习资料以及群交流解答点击即可加入

  1. 利用lxml中的xpath提取信息

    xpath是一门在 xml文档中查找信息的语言,xpath可用来在 xml 文档中对元素和属性进行遍历。对比正则表达式 re两者可以完成同样的工作,实现的功能也差不多,但xpath明显比re具有优势。具有如下优点:(1)可在xml中查找信息 ;(2)支持html的查找;(3)通过元素和属性进行导航

  2. 利用xlsxwriter模块将信息保存只excel

    xlsxwriter是操作excel的库,可以帮助我们高效快速的,大批量的,自动化的操作excel。它可以写数据,画图,完成大部分常用的excel操作。缺点是xlsxwriter 只能创建新文件,不可以修改原有文件,如果创建新文件时与原有文件同名,则会覆盖原有文件。

  3. 爬取思路

    观察发现贝壳网租房信息总共是100页,我们可以分每页获取到html代码,然后提取需要的信息保存至字典,将所有页面的信息汇总,最后将字典数据写入excel。

  4. 爬虫源代码

import requests
import time
from lxml import etree
import xlsxwriter
'''
遇到不懂的问题?Python学习交流群:1136201545满足你的需求,资料都已经上传群文件,可以自行下载!
'''
def get_html(page):
    """获取网站html代码"""
    url = "https://bj.zu.ke.com/zufang/pg{}/#contentList".format(page)
    headers = {
        'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
    }
    response = requests.get(url, headers=headers).text
    return response


def parse_html(htmlcode, data):
    """解析html代码"""
    content = etree.HTML(htmlcode)
    results = content.xpath('///div[@class="content__article"]/div[1]/div')
    for result in results[:]:
        community = result.xpath('./div[1]/p[@class="content__list--item--title twoline"]/a/text()')[0].replace('\n',
                                                                                                                '').strip().split()[
            0]
        address = "-".join(result.xpath('./div/p[@class="content__list--item--des"]/a/text()'))
        landlord = result.xpath('./div/p[@class="content__list--item--brand oneline"]/text()')[0].replace('\n',
                                                                                                          '').strip() if len(
            result.xpath('./div/p[@class="content__list--item--brand oneline"]/text()')) > 0 else ""
        postime = result.xpath('./div/p[@class="content__list--item--time oneline"]/text()')[0]
        introduction = ",".join(result.xpath('./div/p[@class="content__list--item--bottom oneline"]/i/text()'))
        price = result.xpath('./div/span/em/text()')[0]
        description = "".join(result.xpath('./div/p[2]/text()')).replace('\n', '').replace('-', '').strip().split()
        area = description[0]
        count = len(description)
        if count == 6:
            orientation = description[1] + description[2] + description[3] + description[4]
        elif count == 5:
            orientation = description[1] + description[2] + description[3]
        elif count == 4:
            orientation = description[1] + description[2]
        elif count == 3:
            orientation = description[1]
        else:
            orientation = ""
        pattern = description[-1]
        floor = "".join(result.xpath('./div/p[2]/span/text()')[1].replace('\n', '').strip().split()).strip() if len(
            result.xpath('./div/p[2]/span/text()')) > 1 else ""
        date_time = time.strftime("%Y-%m-%d", time.localtime())
        """数据存入字典"""
        data_dict = {
            "community": community,
            "address": address,
            "landlord": landlord,
            "postime": postime,
            "introduction": introduction,
            "price": '¥' + price,
            "area": area,
            "orientation": orientation,
            "pattern": pattern,
            "floor": floor,
            "date_time": date_time
        }

        data.append(data_dict)


def excel_storage(response):
    """将字典数据写入excel"""
    workbook = xlsxwriter.Workbook('./beikeHouse.xlsx')
    worksheet = workbook.add_worksheet()
    """设置标题加粗"""
    bold_format = workbook.add_format({'bold': True})
    worksheet.write('A1', '小区名称', bold_format)
    worksheet.write('B1', '租房地址', bold_format)
    worksheet.write('C1', '房屋来源', bold_format)
    worksheet.write('D1', '发布时间', bold_format)
    worksheet.write('E1', '租房说明', bold_format)
    worksheet.write('F1', '房屋价格', bold_format)
    worksheet.write('G1', '房屋面积', bold_format)
    worksheet.write('H1', '房屋朝向', bold_format)
    worksheet.write('I1', '房屋户型', bold_format)
    worksheet.write('J1', '房屋楼层', bold_format)
    worksheet.write('K1', '查看日期', bold_format)

    row = 1
    col = 0
    for item in response:
        worksheet.write_string(row, col, item['community'])
        worksheet.write_string(row, col + 1, item['address'])
        worksheet.write_string(row, col + 2, item['landlord'])
        worksheet.write_string(row, col + 3, item['postime'])
        worksheet.write_string(row, col + 4, item['introduction'])
        worksheet.write_string(row, col + 5, item['price'])
        worksheet.write_string(row, col + 6, item['area'])
        worksheet.write_string(row, col + 7, item['orientation'])
        worksheet.write_string(row, col + 8, item['pattern'])
        worksheet.write_string(row, col + 9, item['floor'])
        worksheet.write_string(row, col + 10, item['date_time'])
        row += 1
    workbook.close()


def main():
    all_datas = []
    """网站总共100页,循环100次"""
    for page in range(1, 100):
        html = get_html(page)
        parse_html(html, all_datas)
    excel_storage(all_datas)


if __name__ == '__main__':
    main()

5. 信息截图

image

Python爬虫用于从站上抓取数据,例如在贝壳上获取房产信息。要爬取贝壳,你需要使用一些库,如BeautifulSoup、requests和Scrapy等。这里是一个简单的步骤概述: 1. **安装必要的库**:首先确保已安装`requests`库来发送HTTP请求,以及`lxml`或`html.parser`(如果`requests`无法处理HTML)来解析页。 ```bash pip install requests ``` 2. **发送GET请求**:使用`requests.get()`函数获取贝壳的页面内容。 3. **解析HTML**:将响应内容传递给BeautifulSoup,通过CSS选择器或XPath找出需要的数据元素。 ```python from bs4 import BeautifulSoup response = requests.get("https://www贝壳.com/housing/") soup = BeautifulSoup(response.text, 'lxml') ``` 4. **定位数据**:找到包含房产信息的HTML标签,比如`<div>`标签,然后提取属性值。 5. **数据存储**:将提取的数据存储到字典、列表或CSV文件中,或者直接插入数据库(如有必要)。 6. **处理反爬机制**:注意检查贝壳是否有反爬虫策略,可能需要设置User-Agent、添加延迟、使用代理IP等。 7. **异常处理**:编写适当的错误处理代码,应对络连接失败、页面结构变化等问题。 下面是一个基础示例(请注意,这只是一个简化的版本,实际爬取可能需要处理更多复杂情况并遵守站的robots.txt规则): ```python import requests from bs4 import BeautifulSoup def scrape_beiKe(url): headers = { "User-Agent": "Your User Agent Here" } try: response = requests.get(url, headers=headers, timeout=10) response.raise_for_status() # 检查状态码是否正常 soup = BeautifulSoup(response.text, 'lxml') # 使用CSS选择器或其他方式查找房产信息... houses_data = soup.find_all('div', class_='housing-item') # 示例 for house in houses_data: title = house.find('h3').text # 房源标题 price = house.find('span', class_='price').text # 房价 # 存储或打印数据 print(f"房源标题:{title}, 价格:{price}") except (requests.exceptions.RequestException, ValueError) as e: print(f"Error occurred: {e}") url = "https://www贝壳.com/housing/" scrape_beiKe(url) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值