前言
大家早好、午好、晚好吖 ❤ ~欢迎光临本文章

 事情是这样的,小学妹刚毕业参加工作,人生地不熟的,
因为就在我附近上班,所以想找我借宿。。。
想什么呢,都不给住宿费,想免费住?
于是我用Python连夜给她找了个单间,自己去住吧!

开发环境:
开发环境:
-  python 3.8 运行代码 
-  pycharm 2022.3.2 辅助敲代码 专业版 
第三方模块使用:
-  requests 发送请求 pip install requests 
-  parsel 解析数据 pip install parsel 
第三方模块安装:
win + R 输入cmd 输入安装命令 pip install 模块名
(如果你觉得安装速度比较慢, 你可以切换国内镜像源)
代码展示
导入模块
import requests
import parsel
import csv
创建文件
f = open('data.csv', mode='w', encoding='utf-8', newline='')
csv_writer = csv.DictWriter(f, fieldnames=[
    '标题',
    '小区',
    '区域',
    '售价',
    '单价',
    '户型',
    '面积',
    '朝向',
    '装修',
    '楼层',
    '年份',
    '建筑类型',
    '详情页',
])
csv_writer.writeheader()
模拟浏览器
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.0.0 Safari/537.36'
}
请求网址/网站
url = 'https://cs.***.com/ershoufang/'
发送请求
response = requests.get(url=url, headers=headers)
print(response)
解析数据, 提取我们想要的数据内容
使用css: 根据标签属性提取数据内容
把获取到html字符串数据, 转成可解析对象
selector = parsel.Selector(response.text)
获取所有房源信息所在li标签
lis = selector.css('.sellListContent li.clear')
for循环遍历
提取具体房源信息: 标题 / 价格 / 位置 / 户型…
for li in lis:
    title = li.css('.title a::text').get()  # 标题
    info_list = li.css('.positionInfo a::text').getall()
    area = info_list[0]  # 小区名字
    area_1 = info_list[1]  # 地区
    totalPrice = li.css('.totalPrice span::text').get()  # 售价
    unitPrice = li.css('.unitPrice span::text').get().replace('元/平', '').replace(',', '')  # 单价
    houseInfo = li.css('.houseInfo::text').get().split(' | ')  # 信息
    houseType = houseInfo[0]  # 户型
    houseArea = houseInfo[1].replace('平米', '')  # 面积
    houseFace = houseInfo[2]  # 朝向
    fitment = houseInfo[3]  # 装修
    fool = houseInfo[4]  # 楼层
    if len(houseInfo) == 7 and '年' in houseInfo[5]:
        year = houseInfo[5].replace('年建', '')
    else:
        year = ''
    house = houseInfo[-1]  # 建筑类型
    href = li.css('.title a::attr(href)').get()  # 详情页
    dit = {
        '标题': title,
        '小区': area,
        '区域': area_1,
        '售价': totalPrice,
        '单价': unitPrice,
        '户型': houseType,
        '面积': houseArea,
        '朝向': houseFace,
        '装修': fitment,
        '楼层': fool,
        '年份': year,
        '建筑类型': house,
        '详情页': href,
    }
    csv_writer.writerow(dit)
    print(dit)
    # print(title, area, area_1, totalPrice, unitPrice, houseType, houseArea, houseFace, fitment, fool, year, house, href)
括展小知识:
-  <Response [200]>响应对象 200 状态码 表示请求成功
-  解析方法: re:对于字符串数据直接进行解析提取css:根据标签属性提取数据内容xpath:根据标签节点提取数据内容
-  .title a--> 表示定位class类名为title下面a标签
尾语 💝
好了,今天的分享就差不多到这里了!
完整代码、更多资源、疑惑解答直接点击下方名片自取即可。
对下一篇大家想看什么,可在评论区留言哦!看到我会更新哒(ง •_•)ง
喜欢就关注一下博主,或点赞收藏评论一下我的文章叭!!!

最后,宣传一下呀~👇👇👇更多源码、资料、素材、解答、交流皆点击下方名片获取呀👇👇👇










