这几天一直在捣鼓mongoDB的安装费了好多精力啊作业都延迟了
不过勤lan劳duo的我对数据库还是渐渐熟悉起来,虽然还不是很理解,但感觉就像全自动的仓库一样,配合excel的导入导出帅的不行~
然后这周的作业是
目标:爬取小猪短租的页表信息,然后筛选出500元以上的房子
![](https://img.haomeiwen.com/i2468686/fe16ecd51c98c393.png)
价格,标题,出租方式,评论人数,还有地理位置,就是我们要达成的目标啦(还有一个翻页问题)
运行结果
![](https://img.haomeiwen.com/i2468686/19be0e73c8697b1b.png)
五页内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)
难点与收获
- 这是初次在实战使用数据库,感觉还是很好玩的,仓库的功能真的非常强大,但介于现在还不是太熟悉,所以还要看接下来的进步~
- 一个问题是,获取到的评论人数、出租类型和位置在一个<em></em>里还有很多\n和空格,我这里的解决办法是,get_text()之后用split('-')分割成三个部分,然后每个部分去掉多余信息(replace)
- 还有一个问题是筛选房源的时候,字典的price直接get_text()得到的是string,所以为了可以和Int对比,放入字典之前用了Int转换。一开始尝试直接在筛选的时候转换为str,但是str判断时对比的是第一个字符比第一个字符,第二个字符比第二个字符,所以'88'>'500',因此,要对比Int,不能偷懒。
- 没了,为打卡太慢感到抱歉
下次会快点做完的!
网友评论