python爬虫--房产数据爬取并保存本地

 
  

import requests
import csv
from bs4 import BeautifulSoup
headers={'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'}
for i in range(1,10):
link='https://fz.anjuke.com/sale/p'+str(i)+'/#filtersort'
r=requests.get(link,headers=headers)
print(str(i + 1), "页响应状态码:", r.status_code)
soup=BeautifulSoup(r.text,'lxml')
house_list=soup.find_all('li',class_="list-item")
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)

 

几个注意点:

1、with open('test.csv', 'a',newline='',encoding='utf-8-sig')as csvfile:,注意utf8转码,否则数据保存本地会为乱码形式

2、插入标题的方式,数组的写入

 

转载于:https://www.cnblogs.com/leon507/p/10401091.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值