使用 Python Selenium 儲存網頁
我們可以使用 Python 中的 Selenium webdriver 儲存網頁。要儲存頁面,我們首先需要使用 page_source 方法獲取網頁背後的頁面原始碼。
我們必須使用 codecs.open 方法開啟具有特定編碼的檔案。該檔案必須以 w 表示的寫模式和 utf−8 作為編碼型別開啟。然後,使用 write 方法來寫入從 page_source 方法獲取的內容。
語法
n = os.path.join("C:\Users\ghs6kor\Downloads\Test", "PageSave.html")
f = codecs.open(n, "w", "utf−8")
h = driver.page_source
f.write(h)讓我們嘗試儲存以下網頁 −

示例
from selenium import webdriver
import codecs
#set chromedriver.exe path
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
driver.implicitly_wait(0.5)
#maximize browser
driver.maximize_window()
#launch URL
driver.get("https://tutorialspoint.tw/index.htm")
#get file path to save page
n=os.path.join("C:\Users\ghs6kor\Downloads\Test","Page.html")
#open file in write mode with encoding
f = codecs.open(n, "w", "utf−8")
#obtain page source
h = driver.page_source
#write page source content to file
file.write(h)
#close browser
driver.quit()輸出

在瀏覽器中開啟 Page.html 檔案時。

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP