提问人:Manisha Biswas 提问时间:1/29/2023 最后编辑:Max S.Manisha Biswas 更新时间:2/2/2023 访问量:836
使用 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 浏览器的首选项。然后登录网站。登录后,我想下载网页,就像我们从键盘上单击+一样下载。ctrls
下面的代码打开我要下载的所需页面,但不会禁用 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 中使用的替代库。
答:
1赞
Manish
1/29/2023
#1
要保存页面,首先借助该方法获取网页背后的页面源代码。page_source
然后使用该方法打开具有特定编码的文件。文件必须以 w 表示的写入模式打开,编码类型为 utf−8。然后使用 write 方法写入从 page_source 方法获取的内容。codecs.open
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()
评论
0赞
Manisha Biswas
1/30/2023
嗨,Manish,感谢您的回复。我试过你的代码。但是,它正在为我下载源代码,而不是 HTML 资产(CSS、JS 文件)。因此,当我在浏览器中打开下载的文件时,它与我们在服务器上查看的文件不同。
0赞
Manisha Biswas
1/30/2023
#2
我能够解决这个问题,问题是我的代码在浏览器能够下载文件之前就退出了。添加修复了它。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()
评论