聲明:本文參考Python實戰計劃學習筆記2.1:將爬取的數據存入Mongodb
其他參考資料:
Python爬蟲包 BeautifulSoup 學習(十一) CSS 選擇器
python爬蟲:BeautifulSoup 使用select方法詳解
爬取小豬網上上海的租房信息,部分結果如下所示:
image.png
具體代碼如下:
注意運行本代碼前需先啟動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)
## 本代碼經測試無問題