NKUST ITC 108-1 Python[4]
2019/11/19
tags: NKUST ITC
Python 社課
下半學期進度(超理想)
日期 |
內容 |
11/19 |
DOM解析、API |
11/26 |
以下待訂 |
12/17 |
可能會辦活動 |
12/26 |
期末社員大會 |
DOM?
- Document Object Model (文件物件模型)
- 將HTML中的標籤、文字、圖片都定義成物件
- 樹狀結構

HTML
HTML由以下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檔案
| from bs4 import BeautifulSoup |
| |
| with open("index.html") as f: |
| dom = BeautifulSoup(f, 'lxml') |
| print(dom.prettify()) |
尋找單一元素
| |
| 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) |
尋找所有元素
| |
| 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') |
| for tag in tags: |
| 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) |
| |
- 此select()方法會回傳包含所有符合的元素的list,故須以[0]來取出第一個
為何?
在css selector中
- class屬性以一個點'.'表示
- id屬性以一個井字號'#'表示
故 class="content"在css selector中只要用
".content"
就可以表示
做完了不知道要做什麼的做這個
- 從這裡抓出這些資訊

- 這題在範例檔中有答案
API?
- Application Programming Interface
- 應用程式介面
為何需要API?
- 生活情境
- 開放資料 (天氣、交通)
- 開放服務 (Google 日曆、地圖)
- 開發情境
NKUST ITC 108-1 Python[4] https://python-slide.macs1207.dev 2019/11/19 tags: NKUST ITC Python 社課
{"metaMigratedAt":"2023-06-15T01:44:54.354Z","metaMigratedFrom":"Content","title":"NKUST ITC 108-1 Python[4]","breaks":true,"contributors":"[{\"id\":\"0543727d-0e35-443a-a198-84223cf6d534\",\"add\":4293,\"del\":232}]"}