📘
Python web crawler note
  • Introduction
  • 1. 環境安裝與爬蟲的基本
  • 1.1 環境安裝
  • 1.2 IDE設定
  • 1.3 一隻很原始的爬蟲
  • 1.4 幫爬蟲裝煞車
  • 2. 用BeautifuSoup來分析網頁
  • 2.1 BeautifulSoup範例 - 1
  • 2.2 BeautifulSoup說明
  • 2.3 BeautifulSoup範例 - 2
  • 2.4 加入Regular Expression
  • 2.5 Dcard今日十大熱門文章
  • 3. 更多實際的應用
  • 3.1 PTT八卦版今日熱門文章
  • 3.2 Yahoo奇摩電影本週新片
  • 3.3 蘋果日報/自由時報今日焦點
  • 3.4 Google Finance 個股資訊
  • 3.5 Yahoo奇摩字典
  • 4. 基於API的爬蟲
  • 4.1 八卦版鄉民從哪來?
  • 4.2 Facebook Graph API
  • 4.3 imdb電影資訊查詢
  • 4.4 Google Finance API
  • 4.5 台灣證券交易所API
  • 5. 資料儲存
  • 5.1 痴漢爬蟲(PTT表特版下載器)
  • 5.2 儲存成CSV檔案
  • 5.3 儲存至SQLite
  • 6. 不同編碼/文件類型的爬蟲
  • 6.1 非UTF-8編碼的文件
  • 6.2 XML文件
  • 7. 比價爬蟲
  • 7.1 momo購物網爬蟲
  • 7.2 PChome 24h API爬蟲
  • 7.3 比價圖表程式
  • 8. 處理POST請求/登入頁面
  • 8.1 空氣品質監測網
  • 9. 動態網頁爬蟲
  • 9.1 台銀法拍屋資訊查詢
  • 10. 自然語言處理
  • 10.1 歌詞頻率與歌詞雲
Powered by GitBook
On this page

Was this helpful?

2.1 BeautifulSoup範例 - 1

以下這個範例會簡單示範BeautifulSoup的使用方式, 可以邊看html結構邊對照程式碼了解一下各種場合要怎麼去擷取資訊.

import requests
from bs4 import BeautifulSoup


def main():
    url = 'http://blog.castman.net/web-crawler-tutorial/ch2/blog/blog.html'
    resp = requests.get(url)
    soup = BeautifulSoup(resp.text, 'html.parser')

    # The following two lines are the same.
    # print(soup.find('h4'))
    print('Content of the first h4:')
    print(soup.h4)

    # To find the first text content of anchor of h4
    print('\nText content of the first h4:')
    print(soup.h4.a.text)

    print('\nTo find all the h4 text content:')
    h4_tags = soup.find_all('h4')
    for h4 in h4_tags:
        print(h4.a.text)

    print('\nTo find all the h4 text content with class named \'card-title\' :')
    # The following three ways are the same.
    # h4_tags = soup.find_all('h4', {'class': 'card-title'})
    # h4_tags = soup.find_all('h4', 'card-title')
    h4_tags = soup.find_all('h4', class_='card-title')
    for h4 in h4_tags:
        print(h4.a.text)

    print('\nTo find elements with id attribute: ')
    print(soup.find(id='mac-p').text.strip())
    # If the attribute key contains special character, it will occur SyntaxError:
    # print(soup.find(data-foo='mac-p').text.strip())
    # To prevent this, you can do as the following line:
    print(soup.find_all('', {'data-foo': 'mac-foo'}))

    print('\nTo retrieve all the blog post\'s information:')
    divs = soup.find_all('div', 'content')
    for div in divs:
        # If we only use print(div.text) to retrieve the content, it's not easy to handle the information,
        # to make the retrieved data clearly, you can craw the blog page like this:
        print(div.h6.text.strip(), div.h4.a.text.strip(), div.p.text.strip())

    # There is also another good way the retrieve the blog info, by stripped_strings() function,
    # it will return all the text content that are under the parent tag, even wrap by other sub tags.
    # However, the return object of stripped_strings is an iterator object, so it's not human-readable.
    # To solve this, take a look at following code block:
    print('\nTo find all blog contents via stripped_strings function:')
    for div in divs:
        # If you feel it's hard to understand, google "[s for s in subsets(S)]"
        print([s for s in div.stripped_strings])


if __name__ == '__main__':
    main()

輸出如下:

Content of the first h4:
<h4 class="card-title">
<a href="http://www.pycone.com/blogs#pablo">Mac使用者</a>
</h4>

Text content of the first h4:
Mac使用者

To find all the h4 text content:
Mac使用者
給初學者的 Python 網頁爬蟲與資料分析
給初學者的 Python 網頁爬蟲與資料分析
給初學者的 Python 網頁爬蟲與資料分析
給初學者的 Python 網頁爬蟲與資料分析
給初學者的 Python 網頁爬蟲與資料分析

To find all the h4 text content with class named 'card-title' :
Mac使用者
給初學者的 Python 網頁爬蟲與資料分析
給初學者的 Python 網頁爬蟲與資料分析
給初學者的 Python 網頁爬蟲與資料分析
給初學者的 Python 網頁爬蟲與資料分析
給初學者的 Python 網頁爬蟲與資料分析

To find elements with id attribute: 
在Mac環境下安裝Python與Sublime Text3 Read More
[<a data-foo="mac-foo" href="http://www.pycone.com/blogs/mac-python-environment"> <br>Read More </br></a>]

To retrieve all the blog post's information:
開發環境設定 Mac使用者 在Mac環境下安裝Python與Sublime Text3 Read More
資料科學 給初學者的 Python 網頁爬蟲與資料分析 (1) 前言 Read More
資料科學 給初學者的 Python 網頁爬蟲與資料分析 (2) 套件安裝與啟動網頁爬蟲 Read More
資料科學 給初學者的 Python 網頁爬蟲與資料分析 (3) 解構並擷取網頁資料 Read More
資料科學 給初學者的 Python 網頁爬蟲與資料分析 (4) 擷取資料及下載圖片 Read More
資料科學 給初學者的 Python 網頁爬蟲與資料分析 (5) 資料分析及展示 Read More

To find all blog contents via stripped_strings function:
['開發環境設定', 'Mac使用者', '在Mac環境下安裝Python與Sublime Text3', 'Read More']
['資料科學', '給初學者的 Python 網頁爬蟲與資料分析', '(1) 前言', 'Read More']
['資料科學', '給初學者的 Python 網頁爬蟲與資料分析', '(2) 套件安裝與啟動網頁爬蟲', 'Read More']
['資料科學', '給初學者的 Python 網頁爬蟲與資料分析', '(3) 解構並擷取網頁資料', 'Read More']
['資料科學', '給初學者的 Python 網頁爬蟲與資料分析', '(4) 擷取資料及下載圖片', 'Read More']
['資料科學', '給初學者的 Python 網頁爬蟲與資料分析', '(5) 資料分析及展示', 'Read More']

Process finished with exit code 0
Previous2. 用BeautifuSoup來分析網頁Next2.2 BeautifulSoup說明

Last updated 5 years ago

Was this helpful?

原始碼

點我