欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

爬取上海链家二手房信息 源代码共享

最编程 2024-06-28 21:36:01
...
'''
def down_load(page):
    for i in range(1,page+1):
        if i==1:
            url = 'https://cm.lianjia.com/ershoufang/'
        else:
            url = 'https://cm.lianjia.com/ershoufang/pg'+str(i)+'/'
        headers = {'User-Agent':
                               'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36',
                           }
        response = requests.get(url=url,headers=headers)
        response.encoding = 'utf-8'
        tree = etree.HTML(response.text)
        # print(response.text)
        mark_list = tree.xpath('//ul[@class="sellListContent"]//div[@class="info clear"]//div[@class="title"]//a//text()')
        address_list = tree.xpath('//ul[@class="sellListContent"]//div[@class="flood"]//div//a[1]//text()')
        introduce_list = tree.xpath('//ul[@class="sellListContent"]//div[@class="address"]//div//text()')
        Sum_price_list = tree.xpath('//div[@class="priceInfo"]//div[@class="totalPrice totalPrice2"]//span//text()')
        avg_price_list = tree.xpath('//div[@class="priceInfo"]//div[@class="unitPrice"]//span//text()')
        # print(avg_price_list)
        for i in range(len(mark_list)):
            mark = mark_list[i] # 房子的介绍
            address = address_list[i] # 房子的地址
            introduce = introduce_list[i].split('|')
            sum_price = Sum_price_list[i]+'万' # 房子的总价
            avg_price = avg_price_list[i]  # 房子的均价
            unit_type = introduce[0]  # 房子的面积 几室几厅
            acreage = introduce[1]  # 房子的面积
            decorate_type = introduce[2]  # 装修
            flood = introduce[3]   #楼层
            try:
                build_type = introduce[4]  #样式
            except:
                build_type='无数据'
            # dit = {
            #     '介绍':mark,
            #     '地址':address,
            #     '户型':unit_type,
            #     '面积':acreage,
            #     '装修':decorate_type,
            #     '楼层':flood,
            #     '样式':build_type,
            #     '总价':sum_price,
            #     '均价':avg_price,
            # }
            csv_writer.writerow([mark,address,unit_type,acreage,decorate_type,flood,build_type,sum_price,avg_price])

推荐阅读