Python實(shí)戰(zhàn)計(jì)劃學(xué)習(xí)筆記(8)MongoDB存儲(chǔ)

心得

  1. 調(diào)用MongoDB需要導(dǎo)入pymongo庫
  2. MongoDB中也有庫(db)和表(collection)的概念,可以用use,show collections,find()方法來查看
  3. 插入數(shù)據(jù)使用insert_one()方法,可以在循環(huán)中隨時(shí)入庫,不用再使用專用列表來存儲(chǔ),數(shù)據(jù)庫中的數(shù)據(jù)可以保留長期反復(fù)使用。
  4. 數(shù)據(jù)庫中的數(shù)據(jù)可以使用mongoexport.exe導(dǎo)出(如json、csv格式),也可以使用mongoimport將外部數(shù)據(jù)導(dǎo)入數(shù)據(jù)庫
  5. find()方法可以對結(jié)果進(jìn)行條件篩選

我的代碼

找到小豬短租網(wǎng)站的列表頁前三頁上月租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())  #變成數(shù)字才能根據(jù)大小并檢索
        }
        sheet_lines.insert_one(data) #注入數(shù)據(jù)庫


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

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

運(yùn)行結(jié)果

  • 數(shù)據(jù)庫內(nèi)數(shù)據(jù)
1.jpg
  • 篩選結(jié)果
2.jpg
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容