美文网首页
Python实战计划学习笔记(8)MongoDB存储

Python实战计划学习笔记(8)MongoDB存储

作者: 如恒河沙 | 来源:发表于2016-08-30 22:15 被阅读0次

心得

  1. 调用MongoDB需要导入pymongo库
  2. MongoDB中也有库(db)和表(collection)的概念,可以用use,show collections,find()方法来查看
  3. 插入数据使用insert_one()方法,可以在循环中随时入库,不用再使用专用列表来存储,数据库中的数据可以保留长期反复使用。
  4. 数据库中的数据可以使用mongoexport.exe导出(如json、csv格式),也可以使用mongoimport将外部数据导入数据库
  5. find()方法可以对结果进行条件筛选

我的代码

找到小猪短租网站的列表页前三页上月租500元以上的房源信息

from bs4 import BeautifulSoup
import requests
import time
import pymongo
client = pymongo.MongoClient('localhost',27017)
urls = ['http://bj.xiaozhu.com/search-duanzufang-p{}-0/'.format(str(i)) for i in range(1,4,1)]
xiaozhu = client['xiaozhu']
sheet_lines = xiaozhu['sheet_lines']

def get_page_info(url):
    web_data = requests.get(url)
    soup = BeautifulSoup(web_data.text,'lxml')
    titles = soup.select('div.result_btm_con.lodgeunitname > div > a > span')
    links = soup.select('div.result_btm_con.lodgeunitname')
    prices = soup.select('div.result_btm_con.lodgeunitname > span.result_price > i')
    types = soup.select('div.result_btm_con.lodgeunitname > div > em.hiddenTxt')
    for title, type,price,link in zip(titles, types, prices,links):
        data = {
            'title':title.get_text(),
            'link': link.get('detailurl'),
            'unit':type.get_text().split('\n')[1].replace(' ',''),
            #'comment':type.get_text().split('\n')[7].replace(' ',''),
            'price':int(price.get_text())  #变成数字才能根据大小并检索
        }
        sheet_lines.insert_one(data) #注入数据库


for single_url in urls:
    get_page_info(single_url)
    time.sleep(2)

for item in sheet_lines.find({'price':{'$gte':500}}):
    print(item)

运行结果

  • 数据库内数据
1.jpg
  • 筛选结果
2.jpg

相关文章

网友评论

      本文标题:Python实战计划学习笔记(8)MongoDB存储

      本文链接:https://www.haomeiwen.com/subject/pokqettx.html