项目实战一:python爬取安居客各地(此例为福州)二手房数据信息

本项目用python爬取安居客的二手房数据,包括价格,占地面积等,这里只能爬取二手房的信息,如果需要爬取其他比如商铺写字楼的信息,需要对代码进行一些调整,具体代码如下:

import requests #导入请求库

import csv #导入csv库,用于输出csv文件

from bs4 import BeautifulSoup #导入解析库

#添加请求头,模拟浏览器运行

header = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36 Maxthon/5.2.6.1000'}

#设置循环,用来翻页获取每一页的数据,一共取20页进行爬取

for i in range(1, 20):

#给出要爬取的页面链接

link = 'https://fz.anjuke.com/sale/p'+str(i)+'/#filtersort'

#发送请求,获得响应体,r.text是响应体也是网页的html代码

r = requests.get(link, headers=header)

#检查响应是否成功,打印响应码

print(i, "页响应状态码:", r.status_code)

#对获得的响应体(网页源代码)进行解析,解析格式为lxml

soup = BeautifulSoup(r.text, 'lxml')

#寻找所需内容

house_list = soup.find_all('li', class_="list-item")

#建立csv文件

with open('test.csv', 'a', newline='', encoding='utf-8-sig') as csvfile:

w = csv.writer(csvfile)

w.writerow(('标题', '价格', '均价', '面积', '楼层'))

for house in house_list:

temp = []

name = house.find('div', class_='house-title').a.text.strip()

price = house.find('div', class_='pro-price').contents[1].text.strip()

price_ave = house.find('div', class_='pro-price').contents[2].text.strip()

area = house.find('div', class_='details-item').span.text

floor = house.find('div', class_='details-item').contents[5].text

temp = [name, price, price_ave, area, floor]

print(temp)

#按行写入以上解析数据

w.writerow(temp)

最后输出为csv文件,因为爬取的数据量不大,如果需要爬取大量数据,那么自行连接数据库进行存储。


分享到:


相關文章: