筛选价格大于等于500的房源信息
最终结果:
我的代码:
from bs4 import BeautifulSoup
from pymongo import MongoClient
import requests
urls = ['http://bj.xiaozhu.com/search-duanzufang-p{}-0/'.format(str(i)) for i in range(3)]
host = 'localhost'
port = 27017
client = MongoClient(host, port) #利用MongoClient()函数链接mongoDB服务器
smallpig = client['smallpig'] #新建名为smallpig的数据库
house = smallpig['house'] #建立名为house的表
def print_gender(class_name): # 得到房主的性别
if class_name == 'member_ico1':
return '女'
if class_name == 'member_ico':
return '男'
def get_attractions(url): #得到详情页上的租房信息
wb_data = requests.get(url)
soup = BeautifulSoup(wb_data.text, 'lxml')
title = soup.select('div.pho_info > h4')[0].text.strip()
addr = soup.select('div.pho_info > p')[0].get('title')
price = soup.select('div.day_l > span')[0].text
house_pic1 = soup.select('div.pho_show_big > div > img')[0].get('src')
host_pic = soup.select('div.member_pic > a > img')[0].get('src')
host_name = soup.select('div.w_240 > h6 > a')[0].text
host_gender = soup.select('div.member_pic > div')[0].get('class')[0]
data = {
'title':title,
'addr':addr,
'price':int(price), #注意将price的类型进行转化,以便将来对其进行筛选,从网页上抓取下来的是字符串类型
'house_pic1':house_pic1,
'host_pic' :host_pic,
'host_name':host_name,
'host_gender':print_gender(host_gender),
}
house.insert_one(data)
print("Done")
links = []
def get_link(urls): #得到列表页上所有的详情页链接
for url in urls:
wb_data = requests.get(url)
soup = BeautifulSoup(wb_data.text, 'lxml')
link = soup.select('ul > li > a.resule_img_a')
for i in range(len(link)):
links.append(link[i].get('href'))
get_link(urls)
for url in links: #循环得到每个网页上所有链接网页上的信息
get_attractions(url)
for item in house.find({"price" : {"$gte" : 500}}):
print(item)
总结:
-1 在利用mongoDB进行数据的操作时,一定要先打开mongoDB。可以先测试一下,
在mongoDB的安装路径的bin目录下shift+右键->在此处打开命令窗口,输 入mongo,如果出现一下结果,说明已经打开:
-2 爬取的网页可能出现改变导致以前的代码不能正常运行,这时一定要打开要爬取的网站,查看爬取的路径是否正确,对爬取内容的处理是否恰当。