又到了所謂的金山銀四就業季,那找工作的小伙伴宿舍住不慣的話,就會去租房子住,當然也不一定有宿舍,那麼自己找房子的話,肯定是不知道哪哪好。 所以今天教大家用Python來採集本地房源數據,幫助大家篩選好房。 本文涉及知識點 爬蟲基本流程 requests 發送請求 parsel 解析數據 csv 保存 ...
又到了所謂的金山銀四就業季,那找工作的小伙伴宿舍住不慣的話,就會去租房子住,當然也不一定有宿舍,那麼自己找房子的話,肯定是不知道哪哪好。
所以今天教大家用Python來採集本地房源數據,幫助大家篩選好房。
本文涉及知識點
- 爬蟲基本流程
- requests 發送請求
- parsel 解析數據
- csv 保存數據
開發環境
Python 3.8
Pycharm
本文思路
一.、思路分析
找到數據來源
https://cs.anjuke.com/sale/p1/?from=navigation
二、代碼實現
- 發送請求 & 獲取數據
- 解析數據 (提取你想要的數據)
- 保存數據
代碼展示
使用的模塊
import requests import parsel import csv
發送請求 & 獲取數據
headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36' } # 為了防止大家看不懂,我特地錄製了視頻詳細講解,包括完整代碼都打包好了。 # 我還準備了數百本電子書,大量的視頻教程,直接在這個Q裙:708525271 加它自取。 response = requests.get(url, headers=headers, proxies=get_proxies()) html_data = response.text
解析數據
selector = parsel.Selector(html_data) divs = selector.xpath("//div[@class='property']") for div in divs: # 單個房源去提取 title = div.xpath(".//div[@class='property-content']//h3/text()").get().strip() house_type = ''.join(div.xpath(".//div[@class='property-content-info']//span/text()").getall()).strip() area = div.xpath(".//div[@class='property-content-info']/p[2]/text()").get().strip() direction = div.xpath(".//div[@class='property-content-info']/p[3]/text()").get().strip() floor = div.xpath(".//div[@class='property-content-info']/p[4]/text()").get("").strip() year = div.xpath(".//div[@class='property-content-info']/p[5]/text()").get("").strip() price_total = ''.join(div.xpath(".//div[@class='property-price']/p[1]/span/text()").getall()).strip() price_average = div.xpath(".//div[@class='property-price']/p[2]/text()").get().strip() print(title, house_type, area, direction, floor, year, price_total, price_average)
保存數據
csv_writer.writerow([title, house_type, area, direction, floor, year, price_total, price_average])
好了,今天的分享就到這裡結束了,兄弟們快去試試吧!