200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > 爬虫项目--爬取安居客二手房信息

爬虫项目--爬取安居客二手房信息

时间:2024-05-09 07:07:00

相关推荐

爬虫项目--爬取安居客二手房信息

爬虫实战(爬取安居客二手房信息-成都天府新区)

环境:python3.6 pycharm bs4库

解析方式:bs4

需求:爬取二手房信息字段(titile,house_type,build_time,area,address,price,unit_price),并将爬取到的数据导出到excel表格中,当然你也可直接存到数据库。

第一步 分析url:

第一页的url如下

第二页的url:

发现url变化很简单,只需要将第几页{p?} 传递进去就可以获得相应的链接

第二步:分析源代码,并选择合适的解析方式。

由于只爬取成都地区的二手房信息,所以比较简单 ,来到这个页面后,拿到源代码:

可以看到每一页的二手房信息都展示在源代码中,并且用li标签分别写入了每一个房屋的信息,我们所需要的字段信息也都在其中。

第三步: 开始爬取

上我写的代码(接触爬虫不久,写的不好,希望各位多多指教!)

import requestsimport bs4import timeimport randomimport pandas as pdimport openpyxlhouse_info=[]for i in range(1,50):url="/sale/tainfuxinqu/p"+str(i)+"/#filtersort"headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36"}print("开始爬取安居客平台成都二手房第%s页信息....." %(str(i)))response = requests.get(url=url, headers=headers)#生成bs4对象bsoup=bs4.BeautifulSoup(response.text,'lxml')house_list=bsoup.find_all('li', class_="list-item")for house in house_list:#bs4解析文件titile = house.find('a').text.strip()house_type = house.find('div', class_='details-item').span.textbuid_time = house.find('div', class_='details-item').contents[7].textarea = house.find('div', class_='details-item').contents[3].textaddress = house.find('span', class_='comm-address').text.strip()price = house.find('span', class_='price-det').text.strip()unit_price = house.find('span', class_='unit-price').text.strip()pd1= pd.DataFrame({'titile': titile, 'house_type': house_type, 'build_time': buid_time,'area': area, 'address': address, 'price': price, 'unit_price': unit_price},index=[0])house_info.append(pd1)second=random.randrange(3,5)time.sleep(second)house_info2=pd.concat(house_info)house_info2.to_excel('house_info.xlsx',index=False)

导出到excel,用到了python的一个三方库panads,后面也会详细介绍panads库的用法。整体的代码还是比较简单,所以就不多说了。

爬取结果部分截图,这里就不做数据分析了。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。