获取整个页面的屏幕截图并隐藏顶部导航栏并不能像预期的那样工作(Selenium,Python3)

2024-04-19 07:23:46 发布

您现在位置:Python中文网/ 问答频道 /正文

在阅读了thisStackOverflow链接中的答案后,我找到了一种获得整个页面截图的方法。你知道吗

这个解决方案的问题是,我试图隐藏顶部导航栏与每个滚动,但代码似乎没有做到这一点正确。。你知道吗

我之所以要隐藏它是因为它在每个屏幕截图的顶部隐藏了页面的一部分。你知道吗

在我的代码中,我在一组页面上循环,并且对所有页面执行完全相同的工作。在某些情况下,它会隐藏顶栏,在其他一些页面中,它根本没有顶栏。所以生成截图的代码,看起来不太稳定。你知道吗

这是生成屏幕截图的代码的相关部分:

    # loop all pages
    j = 0
    while j < len(all_pages):
        browser.get(base_url + all_pages[j])

        total_width = browser.execute_script("return document.body.offsetWidth")
        total_height = browser.execute_script("return document.body.parentNode.scrollHeight")
        viewport_width = browser.execute_script("return document.body.clientWidth")
        viewport_height = browser.execute_script("return window.innerHeight")
        rectangles = []

        i = 0
        while i < total_height:
            ii = 0
            top_height = i + viewport_height

            if top_height > total_height:
                top_height = total_height

            while ii < total_width:
                top_width = ii + viewport_width

                if top_width > total_width:
                    top_width = total_width

                rectangles.append((ii, i, top_width,top_height))

                ii = ii + viewport_width

            i = i + viewport_height

        stitched_image = Image.new('RGB', (total_width, total_height))
        previous = None
        part = 0

        for rectangle in rectangles:
            if not previous is None:
                browser.execute_script("window.scrollTo({0}, {1})".format(rectangle[0], rectangle[1]))
                time.sleep(0.2)
                browser.execute_script("document.getElementById('header-container').setAttribute('style', 'position: absolute; top: 0px;');")
                time.sleep(0.2)
                time.sleep(0.2)

            file_name = "part_{0}.png".format(part)

            browser.get_screenshot_as_file(file_name)
            screenshot = Image.open(file_name)

            if rectangle[1] + viewport_height > total_height:
                offset = (rectangle[0], total_height - viewport_height)
            else:
                offset = (rectangle[0], rectangle[1])

            stitched_image.paste(screenshot, offset)

            del screenshot
            os.remove(file_name)
            part = part + 1
            previous = rectangle

        stitched_image.save("C:\\Users\\marialena\\source\\repos\\HTMLtoPDF\\all_files\\" + all_pages[j] + ".png",)

        j = j + 1

    browser.quit()

这是脚本执行后生成的两个屏幕截图:

不起作用-每个卷轴的顶部栏: bad-scenario

工作-仅第一次使用顶栏: good-scenario

有人能帮我理解为什么它只隐藏导航栏几次吗?是否需要重置变量?你知道吗


Tags: 代码browserexecutetopscript页面allwidth
1条回答
网友
1楼 · 发布于 2024-04-19 07:23:46

根据@pcalkins的建议,我解决问题的方法是添加以下内容:

browser.execute_script("document.getElementById('header-container').innerHTML = '';")

就在执行屏幕截图的行之前:browser.get_screenshot_as_file(file_name)


现在看不到标题:

no-header-screenshot

相关问题 更多 >