python爬蟲學習筆記 2.9 (使用bs4得案例)

python爬蟲學習筆記 2.9 (使用bs4得案例)

python爬蟲學習筆記 1.1(通用爬蟲和聚焦爬蟲)
python爬蟲學習筆記 1.2 ( HTTP和HTTPS )
python爬蟲學習筆記 1.3 str和bytes的區別
python爬蟲學習筆記 1.4 (Request簡單使用)request安裝
python爬蟲學習筆記 1.5 (Requests深入)
python爬蟲學習筆記 1.6 (HTTP/HTTPS抓包工具-Fiddler)
python爬蟲學習筆記 1.7 (urllib模塊的基本使用)
python爬蟲學習筆記 1.8 (urllib:get請求和post請求)
python爬蟲學習筆記 1.9 (Handler處理器 和 自定義Opener)
python爬蟲學習筆記 2 (非結構化數據和結構化數據提取)
python爬蟲學習筆記 2.1 (正則表達式re模塊)
python爬蟲學習筆記 2.2 (使用正則表達式得爬蟲得簡單案例)
python爬蟲學習筆記 2.3 (XPath與lxml類庫)
python爬蟲學習筆記 2.4 (使用Xpath得案例)
python爬蟲學習筆記 2.5 (json與JsonPath)
python爬蟲學習筆記 2.6 (糗事百科案例)
python爬蟲學習筆記 2.7 (多線程爬蟲案例(初步瞭解))
python爬蟲學習筆記 2.8 (beautifulsoup4)
python爬蟲學習筆記 2.9 (使用bs4得案例)
python爬蟲學習筆記 3 (動態HTML處理和機器圖像識別)
python爬蟲學習筆記 3.1 (動態HTML介紹)
python爬蟲學習筆記 3.2 (Selenium與PhantomJS)
python爬蟲學習筆記 3.#(番外) (selenium和chromedriver使用中得問題)

案例:使用BeautifuSoup4的爬蟲

我們以騰訊社招頁面來做演示:http://hr.tencent.com/position.php?&start=10#a
在這裏插入圖片描述
使用BeautifuSoup4解析器,將招聘網頁上的職位名稱、職位類別、招聘人數、工作地點、發佈時間,以及每個職位詳情的點擊鏈接存儲出來。
在這裏插入圖片描述

# bs4_tencent.py


from bs4 import BeautifulSoup
import urllib
import json    # 使用了json格式存儲

def tencent():
    url = 'http://hr.tencent.com/'
    request = urllib.request.Request(url + 'position.php?&start=10#a')
    response =urllib.request.urlopen(request)
    resHtml = response.read()

    output =open('tencent.json','w')

    html = BeautifulSoup(resHtml,'lxml')

# 創建CSS選擇器
    result = html.select('tr[class="even"]')
    result2 = html.select('tr[class="odd"]')
    result += result2

    items = []
    for site in result:
        item = {}

        name = site.select('td a')[0].get_text()
        detailLink = site.select('td a')[0].attrs['href']
        catalog = site.select('td')[1].get_text()
        recruitNumber = site.select('td')[2].get_text()
        workLocation = site.select('td')[3].get_text()
        publishTime = site.select('td')[4].get_text()

        item['name'] = name
        item['detailLink'] = url + detailLink
        item['catalog'] = catalog
        item['recruitNumber'] = recruitNumber
        item['publishTime'] = publishTime

        items.append(item)

    # 禁用ascii編碼,按utf-8編碼
    line = json.dumps(items,ensure_ascii=False)

    output.write(line.encode('utf-8'))
    output.close()

if __name__ == "__main__":
   tencent()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章