这是一个对我有用的有点脏的解决方案。这个
sleep
滚动不是很好,可能可以改进,但我将把它作为一个开始,看看以后是否有时间收紧它(也可以随意这样做)。
from playwright.sync_api import sync_playwright # 1.37.0
from time import sleep
with open("index.html") as f:
html = f.read()
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.set_content(html)
# focus inside the annoying border to enable scroll
page.click(".document_container")
for i in range(10):
page.mouse.wheel(0, 2500)
sleep(0.5)
# strip out the annoying border that messes up PDF generation
page.evaluate("""() => {
const el = document.querySelector(".document_scroller");
el.parentElement.appendChild(el.querySelector(".document_container"));
el.remove();
}""")
page.emulate_media(media="screen")
page.pdf(path="sales_report.pdf")
browser.close()
两个技巧:
-
单击边界区域内部可以进行滚动,这似乎是加载所有内容所必需的。
-
撕开恼人的边界可以让PDF生成捕获所有页面。当边界存在时,主体上没有滚动,只有内部容器,PDF捕获似乎不理解这一点。