【week 2】day 1:mongodyの簡単な使い方
1883 ワード
1、基礎知識 pymongoライブラリによるpythonとmongodbデータベースの接続 find()関数を使用して、データベース内のデータ を表示します.$lt,$lte,$gt,$gte,$neはそれぞれ,>=,!=
2,practice
子豚の賃貸住宅の最初の3ページの住宅源の情報を取り出して、そして価格が500 RMBより高い住宅源を選別します
The Code:
3、総括と反省
注意すべき点:データベース にデータを挿入する方法辞書の作成 Practice makes perfect!
import pymongo
client = pymongo.MongoClient('localhost', 27017)
walden = client['walden'] #
sheet_lines = walden['sheet_tag'] # sheet
l == less; g ==greater; e == equal; n == not
2,practice
子豚の賃貸住宅の最初の3ページの住宅源の情報を取り出して、そして価格が500 RMBより高い住宅源を選別します
The Code:
import pymongo, requests, time
from bs4 import BeautifulSoup
client = pymongo.MongoClient('localhost', 27017)
walden = client['2_1homework']
sheet_lines = walden['2_1homework']
urls = ['http://bj.xiaozhu.com/search-duanzufang-p{}-0/'.format(i) for i in range(1, 4)]
def get_details(url, data = None):
wb_data = requests.get(url)
soup = BeautifulSoup(wb_data.text, 'lxml')
titles = soup.select('#page_list > ul > li > div.result_btm_con.lodgeunitname > div > a > span')
prices = soup.select('#page_list > ul > li > div > span.result_price > i')
#print(titles, prices)
for i in range(len(titles)):
index = i
title = titles[i].get_text()
price = prices[i].get_text()
data = {
'index' : index,
'title' : title,
'price' : float(price)
}
#print(index, title, price)
sheet_lines.insert_one(data)
def find_price(url, data = None):
for item in sheet_lines.find({'price': {'$gte' : 500}}):
print(item['title'])
for url_single in urls:
get_details(url_single)
find_price(url_single)
time.sleep(2)
3、総括と反省
注意すべき点: