实现python爬取房天下网站所有城市的二手房信息

文章目录

  • 一、相关知识
  • 二、目标
  • 三、实现思路
    • 1.准备工作
    • 2.获取所有城市及对应网址
    • 3.遍历城市,获取所需信息
    • 4.将分解的信息存到csv中
  • 四、完整代码
  • 五、实现结果

一、相关知识

  • BeautifulSoup4使用
  • python将信息写入csv
import csv
with open("11.csv","w") as csvfile: writer = csv.writer(csvfile)writer.writerow(["a","b","c"])writer.writerows([[1,1,1],[2,2,2],[3,3,3]])

二、目标

要求爬取房天下各大城市的二手房信息(www.fang.com)
需爬取所有城市的二手房信息,并存在csv文件中,可以所有数据放在一个文件中,但要记录是哪个省,哪个城市。也可以每个城市的数据放在一个csv文件中。要求爬取每个房源信息包括标题、面积、价格、地址等信息。

三、实现思路

1.准备工作

获取网址并解析

  • 分析房天下各城市各页的网址,得出大部分城市某页的网址为 https://城市.esf.fang.com/?i=30+页数
  • 解析网页为文本:
def response(url, headers):html = requests.get(url=url, headers=headers)html.encoding = html.apparent_encodingreturn html.text

2.获取所有城市及对应网址

解析该网页代码,获取各城市名及链接,并存到列表

3.遍历城市,获取所需信息

  • 先获取每个城市的页数,然后每个城市每页依次解析
  • 通过f12查看网页源代码,分析所需信息

4.将分解的信息存到csv中

四、完整代码

# -*- coding:utf-8 -*-
import requests
from lxml import etree
import re
import csv
from bs4 import BeautifulSoup
from pyasn1.compat.octets import nullheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'}def response(url, headers):html = requests.get(url=url, headers=headers)html.encoding = html.apparent_encodingreturn html.textdef crawl(url, write, headers):html = response(url,headers)soup = BeautifulSoup(html, 'lxml')titles = []  # 存放所有房源标题的列表house_types = []  # 存放所有房源房型的列表sizes = []  # 存放所有房源面积的列表floors = []  # 存放所有房源楼层的列表orientations = []  # 存放所有房源朝向的列表addrs = []  # 存放所有房源地址的列表totals = []  # 存放所有房源总价的列表prices = []  # 存放所有房源单价的列表items1 = soup.find_all('span', class_="tit_shop")for item in items1:titles.append(item.string.split()[0])items2 = soup.find_all('p', class_="tel_shop")for item in items2:house_types.append(item.contents[0].split()[0])sizes.append(item.contents[2].split()[0])floors.append(item.contents[4].split()[0])orientations.append(item.contents[6].split()[0])items4 = soup.find_all('p', class_="add_shop")for item in items4:addrs.append(item.contents[3].string)items5 = soup.find_all('dd', class_="price_right")for item in items5:totals.append(item.contents[1].contents[1].string)prices.append(item.contents[3].string)for i in range(len(titles)):write.writerow([titles[i], house_types[i], sizes[i], floors[i], orientations[i], addrs[i], totals[i],prices[i]])def crawlCity(url2,headers,address_list,hrefs):html2 = response(url2,headers)soup = BeautifulSoup(html2, 'lxml')items = soup.find_all('a', class_="red")for item in items:address_list.append(item.string)hrefs.append(item['href'])def crawlPage(url,headers):html = response(url, headers)items = re.findall("共(.*)页",html)if(len(items)==0):return 0else:for item in items:return itemdef main():totalpage = 0address_list = []hrefs = []url2 = 'https://gz.esf.fang.com/newsecond/esfcities.aspx'crawlCity(url2, headers,address_list,hrefs)key = ['标题', '户型', '面积', '楼层', '朝向', '地址', '总价/万', '单位价格']  # ,'总价','单位价格']for i in range(len(address_list)):with open('{}.csv'.format(address_list[i]), 'a', newline='', encoding='utf-8') as fp:write = csv.writer(fp)write.writerow(key)print('现在爬取%s的二手房信息' % address_list[i])pageurl = "http:"+hrefs[i]if(crawlPage(pageurl,headers)==0):print("该城市无房源信息\n")continueelse:totalpage=int(crawlPage(pageurl,headers))for page in range(1, totalpage+1):pages = (str)(page + 30)new_url = "http:"+hrefs[i]+"/?i="+pagescrawl(new_url, write, headers)print('第%s页爬取完成' % page)print('已完成%s爬取' % address_list[i])print('\n')if __name__ == '__main__':main()

五、实现结果


编程小白,有错误请大佬指出…

本人原创,欢迎转载

Python爬取房天下二手房信息相关推荐

  1. Python爬取房天下租房信息实战

    目录 一.单线程爬虫 二.优化为多线程爬虫 三.使用asyncio进一步优化 四.存入Mysql数据库 (一)建表 (二)将数据存入数据库中 思路:先单线程爬虫,测试可以成功爬取之后再优化为多线程,最 ...

  2. python关于二手房的课程论文_基于python爬取链家二手房信息代码示例

    基本环境配置 python 3.6 pycharm requests parsel time 相关模块pip安装即可 确定目标网页数据 哦豁,这个价格..................看到都觉得脑阔 ...

  3. 详解Python爬取房天下的推荐新楼盘

    点击上方"程序员大咖",选择"置顶公众号" 关键时刻,第一时间送达! 最近一直在关注Python写爬虫相关的知识,尝试了采用requests + Beautif ...

  4. 利用python爬取租房信息_Python爬虫实战(1)-爬取“房天下”租房信息(超详细)

    #前言html 先看爬到的信息:python 今天主要用到了两个库:Requests和BeautifulSoup.因此我先简单的说一下这两个库的用法,提到的都是此文须要用到的.编程 #Requests ...

  5. Python爬虫实战(1)-爬取“房天下”租房信息(超详细)

    前言 先看爬到的信息: 今天主要用到了两个库:Requests和BeautifulSoup.所以我先简单的说一下这两个库的用法,提到的都是此文需要用到的. Requests requests是一个很实 ...

  6. python爬取链家二手房信息

    爬取过程分析: 1.链家网url:https://bj.lianjia.com/ershoufang/pg2/ 显示的二手房信息每个url递增一 2.访问时要加头信息,否则无法访问 3.用beauti ...

  7. 爬虫实战-爬取房天下网站全国所有城市的新房和二手房信息(最新)

    看到https://www.cnblogs.com/derek1184405959/p/9446544.html项目:爬取房天下网站全国所有城市的新房和二手房信息和其他博客的代码,因为网站的更新或者其 ...

  8. Python 使用selenium爬取房天下网站,房源动态信息

    什么是Selenium selenium 是一套完整的web应用程序测试系统,包含了测试的录制(selenium IDE),编写及运行(Selenium Remote Control)和测试的并行处理 ...

  9. Python爬虫案例3:爬取房天下房价等各种信息

    爬取房天下网站,爬取的内容: 区域.小区名.总价.房型.面积.单价.朝向.楼层位置.装修情况.建筑时间.是否有电梯.产权类型.住宅类型.发布日期 信息保存:保存在csv中 数据结果: 1.先建立爬虫项 ...

  10. python爬虫——爬取房天下

    python爬虫--爬取房天下 话不多说,直接上代码! import requests as req import time import pandas as pd from bs4 import B ...

最新文章

  1. 《IT咨询指南》读书笔记一开卷 前言
  2. Microsoft Dynamics CRM 2011 相关-摘自网络
  3. 工信部制定VR行业标准-谋定研究:对话中国经济和信息化
  4. JS正则表达式验证数字非常全
  5. SQL 列转行,即多行合并成一条
  6. 设置webhook_webhook工具实现
  7. macos big sur u盘安装_老款macbook机型欺骗补丁强制安装macOS11 Big Sur图文详解
  8. golang控制台颜色输出(for windows)
  9. Android音视频开发之——音频非压缩编码和压缩编码,神级Android进阶笔记
  10. Java指定屏幕区域截屏
  11. MongoDB——基础篇(文档操作)
  12. Spring 缓存大法
  13. 云桌面优缺点_相比传统PC,云桌面优缺点在哪里?
  14. python 归一化使用
  15. 计算机管理员无法打开软件,win10系统提示管理员已阻止你运行此应用无法打开应用的解决方法...
  16. python五子棋程序教程_python实现五子棋小程序
  17. js处理json数组
  18. JSP实现简单的登录页面实现及代码(非连接数据库)
  19. MySQL的启动、停止、重启
  20. SpringBoot——使用拦截器拦截未登录用户

热门文章

  1. 揭开互联网金融健康发展意见神秘面纱
  2. 文件服务器资源管理器类似软件,好用的小众文件管理软件推荐给大家
  3. PC端 流光溢彩 Arduino
  4. 高级职称计算机考试要求考a级,全国职称计算机考试有哪些级别
  5. 电驴服务器图标显示叉叉,2012年6月最新电驴服务器列表及设置方法
  6. 出现电脑蓝屏代码0x000000ed怎么解决
  7. jmail组件 java,asp空间如何判断jmail组件已经安装?是否支持呢?
  8. Log4J漏洞补丁(ArcGIS Enterprise适用)
  9. 计算机如何进行数值计算
  10. EdgeGallery — MEP — APIs