這幾天一直在搗鼓mongoDB的安裝費了好多精力啊作業(yè)都延遲了
不過勤lan勞duo的我對數據庫還是漸漸熟悉起來,雖然還不是很理解竟块,但感覺就像全自動的倉庫一樣壶运,配合excel的導入導出帥的不行~
然后這周的作業(yè)是
目標:爬取小豬短租的頁表信息,然后篩選出500元以上的房子
小豬短租
價格浪秘,標題蒋情,出租方式,評論人數耸携,還有地理位置棵癣,就是我們要達成的目標啦(還有一個翻頁問題)
運行結果
結果截圖
五頁內500元以上的房子就是這些了(づ ̄ 3 ̄)づ
源代碼
import requests
from bs4 import BeautifulSoup
import time
import pymongo
client = pymongo.MongoClient('localhost',27017)
xiaozhu = client['xiaozhu']
sheet = xiaozhu['sheet']
def get_imformation(path):
resp = requests.get(path)
data = BeautifulSoup(resp.text,'lxml')
prices = data.select('#page_list > ul > li > div.result_btm_con.lodgeunitname > span.result_price > i')
titles = data.select('#page_list > ul > li > div.result_btm_con.lodgeunitname > div > a > span')
kinds_positions = data.select('#page_list > ul > li > div.result_btm_con.lodgeunitname > div > em')
comments = data.select('#page_list > ul > li > div.result_btm_con.lodgeunitname > div > em > span')
for price, title, kind_pos, comment in zip(prices,titles,kinds_positions, comments):
kind_pos1 = kind_pos.get_text().split('-')
kind = kind_pos1[0].replace('\n', '').replace(' ', '')
pos = kind_pos1[-1].replace('\n', '').replace(' ', '')
list = {
'price': int(price.get_text() if price else None),
'title': title.get_text() if title else None,
'comment': comment.get_text() if comment else None,
'kind':kind if kind else None,
'pos':pos if pos else None
}
sheet.insert_one(list)
paths = ['http://bj.xiaozhu.com/search-duanzufang-p{}-0/'.format(i) for i in range(1,6)]
for path in paths:
time.sleep(2)
get_imformation(path)
print(path,'done')
for item in sheet.find({'price':{'$gte':500}}):
print(item)
難點與收獲
- 這是初次在實戰(zhàn)使用數據庫,感覺還是很好玩的夺衍,倉庫的功能真的非常強大狈谊,但介于現在還不是太熟悉,所以還要看接下來的進步~
- 一個問題是沟沙,獲取到的評論人數河劝、出租類型和位置在一個<em></em>里還有很多\n和空格,我這里的解決辦法是矛紫,get_text()之后用split('-')分割成三個部分赎瞎,然后每個部分去掉多余信息(replace)
- 還有一個問題是篩選房源的時候,字典的price直接get_text()得到的是string颊咬,所以為了可以和Int對比务甥,放入字典之前用了Int轉換。一開始嘗試直接在篩選的時候轉換為str喳篇,但是str判斷時對比的是第一個字符比第一個字符敞临,第二個字符比第二個字符,所以'88'>'500'麸澜,因此挺尿,要對比Int,不能偷懶。
- 沒了,為打卡太慢感到抱歉
下次會快點做完的票髓!