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
廣告
© . All rights reserved.