声明:本文参考Python实战计划学习笔记2.1:将爬取的数据存入Mongodb
其他参考资料:
Python爬虫包 BeautifulSoup 学习(十一) CSS 选择器
python爬虫:BeautifulSoup 使用select方法详解
爬取小猪网上上海的租房信息,部分结果如下所示:
具体代码如下:
注意运行本代码前需先启动MongDB数据库服务,启动方法见:
MongoDB+MongoVUE的安装
#coding=utf-8
from bs4 import BeautifulSoup
import requests
import time
import pymongo
def get_detail_info(url, data=None):
# 爬取单条租房信息(标题,图片,房东,日租金,房东性别,房东头像)
wb_data = requests.get(url)
soup = BeautifulSoup(wb_data.text, 'lxml')
time.sleep(2)
# selcet方法的使用请搜索CCS选择器
title = soup.select('h4 > em')[0].get_text() # 标题
address = soup.select('span.pr5')[0].get_text() # 地址
rent = soup.select('div.day_l > span')[0].get_text() #日租金:div是标签,day_I是其属性,span是下一级标签
image = soup.select('#curBigImage')[0].get('src') #图片
lorder_pic = soup.select('div.member_pic > a > img')[0].get('src') #房东头像
lorder_name = soup.select('a.lorder_name')[0].get_text() # 房东名字
lorder_sex = soup.select('#floatRightBox > div.js_box.clearfix > div.w_240 > h6 > span')[0].get('class') # 房东性别
def get_gender(class_name):
if class_name == "member_boy_ico":
return "男"
else:
return "女"
data = {
'标题': title,
'地址': address,
'日租金': rent,
'图片': image,
'房东头像': lorder_pic,
'房东姓名': lorder_name,
'房东性别': get_gender(lorder_sex)
}
print(data)
return data
def get_all_data(urls): # 传入主页链接集(本例是3页,3个链接)
all_data = []
for url in urls: #遍历链接
wb_data = requests.get(url) #获取链接内容
soup = BeautifulSoup(wb_data.text, 'lxml') #解析链接
links = soup.select('#page_list > ul > li > a') # 使用CCS选择器,选取每个租房信息的链接
for link in links:
href = link.get('href')
all_data.append(get_detail_info(href)) #调用get_detail_info函数,将抓取的租房信息添加进列表all_data
return all_data
# 定义数据库
client = pymongo.MongoClient('localhost', 27017) # 建立与数据库的连接
rent_info = client['rent_info'] #创建数据库rent_info
sheet_table = rent_info['sheet_table'] # 创建表单sheet_table
k=input("please enter the num of page that you want to crawl:")
urls = ['http://sh.xiaozhu.com/search-duanzufang-p{}-0/'.format(str(i)) for i in range(1, k+1)]
# 设置3页的租房信息的链接
datas = get_all_data(urls) #调用get_all_data函数,将抓取的信息存入列表datas
for item in datas:
sheet_table.insert_one(item) #将数据存入数据库
# for item in sheet_table.find():
# 筛选出日租金大于等于500的租房信息,并打印出来
# if int(item['日租金']) >= 500:
# print(item)
## 本代码经测试无问题