Python實戰計劃學習筆記示例(3) 爬取租房信息

學習Python第二節課,爬取商品信息

1 目標任務

1.1進入小豬租(http://bj.xiaozhu.com/search-duanzufang-p1-0/),從列表頁面進入第一個詳情頁,爬取“標題”、“地址”、“日租金”、“第一張房源圖片鏈接”、‘“房東圖片鏈接”、“房東性別”、“房東名字”。

目標任務1-1
目標任務1-2

1.2爬取10頁面房源信息

目標任務2

2 爬取結果

爬取結果.jpg

3 我的代碼

#! /usr/bin/env python
# -*- coding:utf-8 -*-

from bs4 import BeautifulSoup
import requests

def get_links(url):

    # 向服務器請求獲取網頁內容并賦值給wb_data
    wb_data = requests.get(url)

    # 解析網頁
    soup = BeautifulSoup(wb_data.text, 'lxml')

    # 獲取列表頁商品信息
    links = soup.select('#page_list > ul > li > a ')

    # 獲取10個列表頁商品的內容
    for link in links:
        href = link.get('href')
        get_detail_info(href)

# 判斷房東性別
def get_lorder_sex(class_name):
    if class_name == ['member_ico']:
        return '男'
    else:
        return '女'

def get_detail_info(url):
    wb_data = requests.get(url)
    soup = BeautifulSoup(wb_data.text,'lxml')

    # 獲取標題
    titles = soup.select('body > div.wrap.clearfix.con_bg > div.con_l > div.pho_info > h4 > em')

    # 獲取地址
    addresss = soup.select('body > div.wrap.clearfix.con_bg > div.con_l > div.pho_info > p > span')

    # 獲取價格
    prices = soup.select('#pricePart > div.day_l > span')

    # 獲取圖片
    images = soup.select('#curBigImage')

    # 獲取房東頭像
    avartars = soup.select('#floatRightBox > div.js_box.clearfix > div.member_pic > a > img')

    # 獲取房東姓名
    names = soup.select('#floatRightBox > div.js_box.clearfix > div.w_240 > h6 > a')

    # 獲取房東性別
    sexs = soup.select('#floatRightBox > div.js_box.clearfix > div.w_240 > h6 > span')

    # 從標簽中提取內容
    for title, address, price, image, avartar, name, sex in zip(titles, addresss, prices, images, avartars, names, sexs):
        data = {
            'title':title.get_text(),
            'address':address.get_text(),
            'price':price.get_text(),
            'image':image.get('src'),
            'avartar':avartar.get('src'),
            'name':name.get_text(),
            'sex':get_lorder_sex(sex.get('class'))
        }
    print(data)

# 批量獲取鏈接
urls = ['http://bj.xiaozhu.com/search-duanzufang-p{}-0/'.format(number) for number in range(1,10)]
for single_url in urls:
    get_links(single_url)

4 總結

4.1 使用request函數,向服務器請求網頁內容
4.2 使用format語句、for語句批量獲取網頁地址
4.3 在代碼執行過程中,語句逐條執行,不可亂序,視乎不像C語言有函數的入口。
若將批量獲取鏈接的代碼放到 def get_links(url)語句的前端會進行報錯。

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

推薦閱讀更多精彩內容