學習爬蟲第二周,對Mongodb進行學習。
代碼如下:
#!/usr/bin/env python
# coding: utf-8
__author__ = 'lucky'
from bs4 import BeautifulSoup
import requests
import pymongo
client = pymongo.MongoClient('localhost',27017)#激活本地數據庫 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()), #取整數,方便數據庫處理
}
sheet_tab.insert_one(data) #寫每行數據
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 查詢數據庫數據 和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
數據庫情況:
database.png
總結:
- 復習了網頁爬蟲的相關知識。
- 對數據庫的操作和指令進行了學習,還需要繼續練習。