python链家上海

# -*- coding: utf-8 -*-
# @Time    : 2022/12/23 20:46

import re  # 正则表达式
import json
from numpy import *  # 创建给定类型的矩阵,并初始化为0
import urllib.request,urllib.error

location  = re.compile(r'data-el="region">(.*?)</a>', re.S)
houseInfo = re.compile(r'class="houseIcon"></span>(.*?)</div>', re.S)
years = re.compile(r'')
priceall = re.compile(r'<div class="priceInfo">(.*?)</span>', re.S)
priceaverage = re.compile(r'data-price="(.*?)"',re.S)
four_location_C = ['徐家汇','浦东','浦西','闵行']
four_location_P = ['xujiahui','pudong','puxi','minhang']
def get_data():
    '''
    通过循环获取租房信息
    :return:
    '''
    four_lo = {}
    for j in range(4):
        five_page = {} #爬取5页
        k = 1
        for i in range(1, 6):
            print('正在爬取第%d页' % (i))
            # 爬取成都链家网租房信息
            baseurl = 'https://jn.lianjia.com/ershoufang/pg' + str(i) + 'rs' + four_location_P[j] + '/'
            url = baseurl
            header = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'}
            request = urllib.request.Request(url, headers=header)
            html = ""
            response = urllib.request.urlopen(request)
            html = response.read().decode("utf-8")

            bian1 = re.compile(r'\u2022')
            bian2 = re.compile(r'\xa9')
            con = re.sub(bian1, '', html)
            con = re.sub(bian2, '', con)

            locat = re.findall(location, con)
            house = re.findall(houseInfo, con)
            price1 = re.findall(priceall, con)
            price2 = re.findall(priceaverage, con)

            #one_page = []
            for i in range(len(locat)):
                one = {}
                one['楼盘'] = locat[i]
                one['总价'] = re.findall("[0-9]+", price1[i])[1] + '万'
                one['面积'] = house[i].split('|')[1]
                print(house[i])
                if '年建' in house[i]:
                    t = house[i].index('年建')
                    one['建造时间'] = house[i][t - 4:t]
                else:
                    one['建造时间'] = 0
                one['单价']=price2[i] + '元/平'
                five_page[k]=one
                k = k+1

        four_lo[four_location_C[j]]=five_page
    with open("北京二手房.json", "w", encoding='utf-8') as f:  ## 设置'utf-8'编码
        f.write(json.dumps(four_lo, ensure_ascii=False,indent=4 ))


get_data()


### 如何使用Python编写爬虫程序来爬取网的数据 为了实现从网上抓取数据的目标,可以采用 `requests` 和 `BeautifulSoup` 库来进行基本的网页请求和解析操作。如果目标更复杂,则可以选择框架如 Scrapy 来构建更加健壮的爬虫。 以下是基于 Python 的简单爬虫示例代码: #### 数据采集部分 通过模拟 HTTP 请求访问网,并提取所需字段的信息。 ```python import requests from bs4 import BeautifulSoup def fetch_lianjia_data(city, district, page=1): url = f"https://{city}.lianjia.com/ershoufang/{district}/pg{page}" headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' } response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, 'html.parser') house_list = [] items = soup.find_all('div', class_='info clear') # 找到所有的房屋信息条目 for item in items: title = item.find('a', class_='noresultRecommend').get_text(strip=True) if item.find('a', class_='noresultRecommend') else None price_total = item.find('div', class_='totalPrice').find('span').text.strip() if item.find('div', class_='totalPrice') else None unit_price = item.find('div', class_='unitPrice').get_text(strip=True).split(' ')[0].strip() if item.find('div', class_='unitPrice') else None house_info = { "title": title, "price_total": price_total, "unit_price": unit_price } house_list.append(house_info) return house_list ``` 上述函数实现了分页爬取指定城市的二手房列表功能[^1]。它会返回每套房子的基本信息字典集合。 #### 存储至Excel文件 当完成数据抓取之后,可利用 pandas 将其导出为 Excel 表格形式存储下来。 ```python import pandas as pd data = fetch_lianjia_data("sh", "pudong") # 上海市浦东新区作为例子 df = pd.DataFrame(data) output_file_path = "./lianjia_houses.xlsx" df.to_excel(output_file_path, index=False) print(f"Data has been saved to {output_file_path}") ``` 此段脚本负责把之前获得的结果转换成 DataFrame 对象再保存成为 .xlsx 文件[^4]。 需要注意的是,在实际开发过程中还需要考虑反爬机制处理、异常捕获等问题[^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值