環境:win10,anaconda3(python3.5)
爬取對象網站:鏈家上海租房
方法一:利用requests擷取網頁資訊,再利用正則提取資料,並將結果儲存到csv檔案。
代碼地址:代碼
抓取到的資料如下所示:
從左往右依次是:房屋連結、房屋描述、房屋布局、房屋大小、所在區、所在區的具體地區、房屋樓層數、交通訊息、看房時間、房租(/月)、上架時間以及當前有多少人看過該房屋。
方法二:利用requests擷取網頁資訊,再用BeautifulSoup解析資料,並用MongoDB儲存結果。
主要爬取的資料有:房屋連結、房屋描述、小區、戶型、面積,所在地區、房租、交通訊息、多少人看過等。
鏈家只提供100頁資料,所以只爬取這100頁資料。
審查元素髮現每個li標籤就是一個房源
而在每個li標籤中,房屋資訊全在class=info-panel中,所以class=info-panel中的資料即為我們需要抓取的資料區塊。
用BeautifulSoup解析資料,
soup = BeautifulSoup(html, 'lxml')
for item in soup.select('.info-panel'):
一個個裝載資料即可
houseUrl = item.find("h2").a["href"]
title = item.find("h2").a["title"]
。。。。
然後將抓取好的資料,存入資料庫。
先為每個item產生一個鏈表:
yield {
'_id': id,
'houseUrl': houseUrl,
'houseDescription': title,
'xiaoqu': xiaoqu,
'huxing': huxing,
'mianji': mianji,
'area': area,
'sub_area': sub_area,
'traffic': subway,
'price': price,
'data': data,
'watchedPersons': watched
}
初始化設定MongoDB(windows配置MongoDB移步至:win10 配置MongoDB以及視覺化檢視Robo 3T)
client = pymongo.MongoClient('mongodb://localhost:27017')
db_name = 'lianjia_zufang_shanghai'
db = client[db_name]
collection_set01 = db['set01']
再依次將資料存入資料庫中
for item, index in parse_one_page(html, index):
collection_set01.save(item)
儲存到資料庫中的資料如下:
完整代碼:代碼
總之就是寫好自己的model類,所有資料一股腦搗鼓進去,然後save。
只是個爬蟲小程式,代碼寫得比較簡單,只是能跑起來而已。