changed 6 years ago
Linked with GitHub

NKUST ITC 108-1 Python[4]

https://python-slide.macs1207.dev
2019/11/19
tags: NKUST ITC Python 社課


Github


下半學期進度(超理想)

日期 內容
11/19 DOM解析、API
11/26 以下待訂
12/17 可能會辦活動
12/26 期末社員大會

DOM解析


DOM?

  • Document Object Model (文件物件模型)
  • 將HTML中的標籤、文字、圖片都定義成物件
  • 樹狀結構

HTML

HTML由以下3種東西組成

  1. 元素
  2. 屬性
  3. 屬性值

<!DOCTYPE html> <html> <body> <h1>My First Heading</h1> <div class="content">My first paragraph.</div> </body> </html>

<div class="content">My first paragraph.</div>
  • 以此為例,<div>與</div>為標籤
    • 兩個成對的標籤組成一個元素
  • 兩標籤中夾帶內容
  • class為屬性名稱
  • content則為屬性值

採用BeautifulSoup

pip install beautifulsoup4
from bs4 import BeautifulSoup import requests rs = requests.get('https://movies.yahoo.com.tw/movie_intheaters.html') dom = BeautifulSoup(rs.text, 'lxml') print(dom.prettify()) # 輸出排版後的HTML

也可以直接讀取html檔案

from bs4 import BeautifulSoup with open("index.html") as f: dom = BeautifulSoup(f, 'lxml') print(dom.prettify()) # 輸出排版後的HTML

尋找單一元素

# find()尋找單一元素 from bs4 import BeautifulSoup import requests url = 'http://quotes.toscrape.com/' rs = requests.get(url) dom = BeautifulSoup(rs.text, 'lxml') print(dom.find('p').text)

尋找所有元素

# find_all()尋找所有元素 from bs4 import BeautifulSoup import requests url = 'http://quotes.toscrape.com/' rs = requests.get(url) soup = BeautifulSoup(rs.text, 'lxml') tags = soup.find_all(class_='text') # 找出所有class為text的資料 for tag in tags: # 搭配for顯示class為text的內容 print(tag.text)

尋找所有超連結

from bs4 import BeautifulSoup import requests url = 'http://quotes.toscrape.com/' rs = requests.get(url) soup = BeautifulSoup(rs.text, 'html.parser') tags = soup.find(class_='quote').find_all('a') for tag in tags: print(tag['href'])

更好用的css selector

<!DOCTYPE html> <html> <body> <h1>My First Heading</h1> <div class="content">My first paragraph.</div> </body> </html>

如上的html文件,只要這樣就能取出div的內容

print(dom.select(".content")[0].text) # Output: My first paragraph.
  • 此select()方法會回傳包含所有符合的元素的list,故須以[0]來取出第一個

為何?

在css selector中

  • class屬性以一個點'.'表示
  • id屬性以一個井字號'#'表示

故 class="content"在css selector中只要用

".content"

就可以表示


練習1

  • 這裡抓出
    • 當前溫度
    • 體感溫度
    • 濕度
    • 降雨量

做完了不知道要做什麼的做這個

  • 這裡抓出這些資訊
  • 這題在範例檔中有答案

API


API?

  • Application Programming Interface
  • 應用程式介面
    • 定義一個讓程式間能相互溝通存取的介面

為何需要API?

  • 生活情境
    • 開放資料 (天氣、交通)
    • 開放服務 (Google 日曆、地圖)
  • 開發情境
    • 作業系統 API
    • 軟硬體 API


又以天氣為例

  • 這個API DEMO
    • 三民區id: 264
  • 結果須包含
    • 當前溫度
    • 體感溫度
    • 濕度
    • 降雨量

換各位練習看看


延伸閱讀

RESTful API


DevFest 高雄場


Discord


Telegram


作者


參考資料

Select a repo