我想自动化“将网页保存为完整”功能,并将其用于我拥有的约 100 个 URL。我更愿意通过 Chrome 上的脚本来完成此操作,但我了解 Python,因此如果这最终是一种更快/更简单的方法,那么我愿意接受建议。 TIA
我尝试了几个 Chrome 扩展,但大多数都无法加载图像或只是保存 HTML,完全省略 CSS、脚本和资源。
我还尝试使用 ChromeDriver 在 Python 上通过 Selenium 和 BeautifulSoup 进行抓取,但我无法让它工作。
确保所有元素正确加载以避免丢失资源:
尝试一下这个代码
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from
selenium.webdriver.support.ui
import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from awaitility import await
# ... your code for setting up ChromeDriver and options
urls = [
"https://example.com/page1",
"https://example.com/page2",
# ... your other URLs
]
for url in urls:
driver.get(url)
# Wait for elements to load using Awaitility
@await.poll_interval(1, 5) # Retry every second, for a maximum of 5 seconds
def all_elements_loaded():
return driver.execute_script("return document.readyState") == "complete"
await(all_elements_loaded())
# Now save the complete page
driver.execute_script("window.print();")
根据您的需要更改此代码,并更改 url 的
尝试在 python 中使用 Playwright 和 requests 您还可以使用 wget 下载文件和网站,并提供递归下载选项
避免向服务器发送太多请求或未经许可抓取敏感数据。
避免一次向服务器发送太多查询或未经授权收集私人信息。