- Python資料科學教程
- Python資料科學 - 首頁
- Python資料科學 - 入門
- Python資料科學 - 環境搭建
- Python資料科學 - Pandas
- Python資料科學 - NumPy
- Python資料科學 - SciPy
- Python資料科學 - Matplotlib
- Python資料處理
- Python資料操作
- Python資料清洗
- Python處理CSV資料
- Python處理JSON資料
- Python處理XLS資料
- Python關係型資料庫
- Python NoSQL資料庫
- Python日期和時間
- Python資料整理
- Python資料聚合
- Python讀取HTML頁面
- Python處理非結構化資料
- Python分詞
- Python詞幹提取和詞形還原
- Python資料視覺化
- Python圖表屬性
- Python圖表樣式
- Python箱線圖
- Python熱力圖
- Python散點圖
- Python氣泡圖
- Python 3D圖表
- Python時間序列
- Python地理資料
- Python圖資料
Python - 讀取HTML頁面
名為Beautiful Soup的庫。使用這個庫,我們可以搜尋HTML標籤的值,並獲取特定資料,例如頁面的標題和頁面的標題列表。
安裝Beautiful Soup
使用Anaconda包管理器安裝所需的包及其依賴包。
conda install Beaustifulsoap
讀取HTML檔案
在下面的例子中,我們向一個URL發出請求,將其載入到Python環境中。然後使用html解析器引數讀取整個HTML檔案。接下來,我們列印HTML頁面的前幾行。
import urllib2
from bs4 import BeautifulSoup
# Fetch the html file
response = urllib2.urlopen('https://tutorialspoint.tw/python/python_overview.htm')
html_doc = response.read()
# Parse the html file
soup = BeautifulSoup(html_doc, 'html.parser')
# Format the parsed html file
strhtm = soup.prettify()
# Print the first few characters
print (strhtm[:225])
執行上述程式碼後,將產生以下結果。
<!DOCTYPE html> <!--[if IE 8]><html class="ie ie8"> <![endif]--> <!--[if IE 9]><html class="ie ie9"> <![endif]--> <!--[if gt IE 9]><!--> <html> <!--<![endif]--> <head> <!-- Basic --> <meta charset="utf-8"/> <title>
提取標籤值
我們可以使用以下程式碼從標籤的第一個例項中提取標籤值。
import urllib2
from bs4 import BeautifulSoup
response = urllib2.urlopen('https://tutorialspoint.tw/python/python_overview.htm')
html_doc = response.read()
soup = BeautifulSoup(html_doc, 'html.parser')
print (soup.title)
print(soup.title.string)
print(soup.a.string)
print(soup.b.string)
執行上述程式碼後,將產生以下結果。
Python Overview - 技術教學 Python Overview None Python is Interpreted
提取所有標籤
我們可以使用以下程式碼從標籤的所有例項中提取標籤值。
import urllib2
from bs4 import BeautifulSoup
response = urllib2.urlopen('https://tutorialspoint.tw/python/python_overview.htm')
html_doc = response.read()
soup = BeautifulSoup(html_doc, 'html.parser')
for x in soup.find_all('b'): print(x.string)
執行上述程式碼後,將產生以下結果。
Python is Interpreted Python is Interactive Python is Object-Oriented Python is a Beginner's Language Easy-to-learn Easy-to-read Easy-to-maintain A broad standard library Interactive Mode Portable Extendable Databases GUI Programming Scalable
廣告