python爬虫---一键采集ftx网站上的所有房源信息

一、网页分析

网页中房子信息都在//div[@class=“shop_list shop_list_4”]/dl[@class=“clearfix”]里面。
所有的信息
以标题为例用xpath-helper插件分析。
在这里插入图片描述
在这里插入图片描述

二、代码实战

import requests
import parsel
import csv

#https://xian.esf.fang.com/
#https://xian.esf.fang.com/house/i31/
#https://xian.esf.fang.com/house/i32/
#https://xian.esf.fang.com/house/i33/
#https://xian.esf.fang.com/house/i34/

url = 'https://xian.esf.fang.com/house/i37/'
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'
}

response = requests.get(url=url,headers=headers)
response.encoding = 'utf-8'
data = response.text
print(data)
selector = parsel.Selector(data)
dls = selector.xpath('//div[@class="shop_list shop_list_4"]/dl[@class="clearfix"]')
print(dls)
for dl in dls:
    name = dl.xpath('.//h4[@class="clearfix"]/a/span/text()').get()
    if name:
        name = dl.xpath('.//h4[@class="clearfix"]/a/span/text()').get().strip()
        #print(name.strip())
    addr = dl.xpath('.//p[@class="add_shop"]/span/text()').get()
    if addr:
        #print(addr)
        addr = dl.xpath('.//p[@class="add_shop"]/span/text()').get()
    price = dl.xpath('.//dd[@class="price_right"]/span/text()').getall()
    price_w = dl.xpath('.//dd[@class="price_right"]/span/b/text()').getall()
    #print(price_w)
    if price:
        price[1] = price_w[0]
        #print("|".join(price))
        price = "|".join(price)
    room = dl.xpath('.//p[@class="tel_shop"]/text()').getall()
    area = dl.xpath('.//p[@class="tel_shop"]/i').re("[\d~㎡]+")
    if room:
        room = "".join(room).strip()
        str = room.split()
        #print("|".join(str))
        room = "|".join(str)
    orig_url = dl.xpath('.//h4[@class="clearfix"]/a/@href').get()
    if orig_url:
        #print(orig_url)
        orig_url = dl.xpath('.//h4[@class="clearfix"]/a/@href').get()
    print([name,price,addr,room,orig_url])

    with open('house.csv',mode='a',encoding='utf-8',newline='') as f:
        csv_write = csv.writer(f)
        csv_write.writerow([name,price,addr,room,orig_url])

爬取结果:
在这里插入图片描述
保存下来的csv文件。
在这里插入图片描述
备注:本案例在爬取第二页的时候出现了抓取内容为空,后面解决了会更新文章,如果你有好的解决办法,欢迎留言交流。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

他是只猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值