簡體   English   中英

使用 Selenium 和 Python 將整個網頁下載為 HTML(包括 HTML 資產)而不另存為彈出窗口

[英]Download entire webpage as HTML (including the HTML assets) without save as pop up using Selenium and Python

我正在嘗試抓取一個網站並將所有網頁下載為 .html 文件(包括所有 HTML 資產),以便本地下載的頁面在服務器中打開時一樣。

當前使用 Selenium、Chrome Webdriver 和 Python。

方法:

我嘗試更新 chrome 瀏覽器的首選項。 然后登錄網站。 登錄后我想下載網頁,就像我們通過單擊鍵盤上的ctrl + s下載一樣。

下面的代碼打開了我想要下載的所需頁面,但沒有禁用 Windows 的另存為彈出窗口,也沒有將頁面下載到指定路徑。

from selenium import webdriver 
import pyautogui
chrome_options = webdriver.ChromeOptions()
preferences = {
"download.default_directory":"C:\\Users\\pathtodir",
               
"download.prompt_for_download": False,
              
"download.directory_upgrade": True,
               
"safebrowsing.enabled": True
}

chrome_options.add_experimental_option("prefs", preferences)
    
driver = webdriver.Chrome(options=chrome_options)
driver.get(***URL to the website***)
driver.find_element("xpath", '//*[@id="id_username"]').send_keys('username')
 
driver.find_element("xpath", '//*[@id="id_password"]').send_keys('password')

driver.find_element("xpath", '//*[@id="datagrid- 
0"]/div[2]/div[1]/div[1]/table/tbody/tr[1]/td[2]/a').click()
pyautogui.hotkey('ctrl', 's')

pyautogui.typewrite('hello1' + '.html')
    
pyautogui.hotkey('enter')

有人可以幫助我了解我做錯了什么嗎? 請建議python中是否還有其他替代庫可以使用。

要保存頁面,首先要借助page_source方法獲取網頁后面的頁面源。

然后使用codecs.open方法打開具有特定編碼的文件。 該文件必須以 w 表示的寫入模式和utf−8編碼類型打開。 然后使用write方法寫入從page_source方法獲取的內容。

from selenium import webdriver
import codecs


driver = webdriver.Chrome(executable_path="path to chromedriver.exe")
driver.implicitly_wait(0.5)

driver.get(***URL to the website***)
h = driver.page_source

n=os.path.join("C:\ANYPATH","Page.html")
f = codecs.open(n, "w", "utf−8")

f.write(h)
driver.quit()

我能夠解決這個問題,主要問題是我的程序在瀏覽器能夠下載文件之前就退出了。 添加 time.sleep() 修復它。

更新代碼:

from selenium import webdriver 
import pyautogui

driver.get(***URL to the website***)
driver.find_element("xpath", '//*[@id="id_username"]').send_keys('username')
 
driver.find_element("xpath", '//*[@id="id_password"]').send_keys('password')

driver.find_element("xpath", '//*[@id="datagrid- 
0"]/div[2]/div[1]/div[1]/table/tbody/tr[1]/td[2]/a').click()
FILE_NAME = r'C:\ANYPATH\Page.html'

pyautogui.typewrite(FILE_NAME)
pyautogui.press('enter')

time.sleep(10)

driver.quit()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM