Python實戰(zhàn)計劃學習筆記:week2_1 在MongoDB中篩選房源

學習爬蟲第二周,對Mongodb進行學習。

代碼如下:

#!/usr/bin/env python
# coding: utf-8
__author__ = 'lucky'

from bs4 import BeautifulSoup
import requests
import pymongo

client = pymongo.MongoClient('localhost',27017)#激活本地數(shù)據(jù)庫 port

info_house = client['info_house'] #類似于excel的文件名
sheet_tab = info_house['sheet_tab'] #類似于excel的文件名中的sheet表


#每個鏈接打開后的信息
def get_info(url):
    wb_data = requests.get(url)
    Soup = BeautifulSoup(wb_data.text,'lxml')
    titles =Soup.select('div.con_l > div.pho_info > h4 > em')
    rents = Soup.select('#pricePart > div.day_l > span')
    for title,rent in zip(titles,rents):
        data={
        "title":title.get_text(),
        "rent":int(rent.get_text()),  #取整數(shù),方便數(shù)據(jù)庫處理
        }
        sheet_tab.insert_one(data)  #寫每行數(shù)據(jù)

def get_links(one_url):
    wb_data = requests.get(one_url)
    Soup = BeautifulSoup(wb_data.text,'lxml')
    links = Soup.select('#page_list > ul > li > a')
    for link in links:
        href = link.get("href")
        get_info(href)

url_links = ["http://bj.xiaozhu.com/search-duanzufang-p{}-0/".format(number) for number in range(1, 4)]

for url in url_links:
    get_links(url)

#find 查詢數(shù)據(jù)庫數(shù)據(jù) 和python字典用法很像
# $lt/$lte/$gt/$gte/$ne 依次等于</<=/>/>=/!= (l:less,g:greater,e:equal,n:not)
for item in sheet_tab.find({'rent':{'$gte':500}}):#
    print(item)

運行效果:

大于等于500的房屋信息.png

數(shù)據(jù)庫情況:

database.png

總結(jié):

  • 復習了網(wǎng)頁爬蟲的相關(guān)知識。
  • 對數(shù)據(jù)庫的操作和指令進行了學習,還需要繼續(xù)練習。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容