爬蟲入門練習(三)爬取小豬租房網信息

聲明:本文參考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)


## 本代碼經測試無問題

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • # Python 資源大全中文版 我想很多程序員應該記得 GitHub 上有一個 Awesome - XXX 系列...
    aimaile閱讀 26,595評論 6 427
  • 爬蟲是一個比較容易上手的技術,也許花5分鐘看一篇文檔就能爬取單個網頁上的數據。但對于大規模爬蟲,完全就是另一回事,...
    真依然很拉風閱讀 9,731評論 5 114
  • 我為什么不該痛快地好好活一次呢?人一生就只能活一次,一旦錯過了機會,什么都完了。 曾樹生 巴金《寒夜》
    素兮0728閱讀 278評論 0 0
  • 簡而言之,一個程序至少有一個進程,一個進程至少有一個線程.線程的劃分尺度小于進程,使得多線程程序的并發性高。另外,...
    乖乖果效36閱讀 261評論 0 0