selenium截图网站页面

作者: root007 分类: Linux 发布时间: 2021-04-27 14:09
from selenium import webdriver
from selenium.webdriver.chrome.options import Options



def get_image(url, pic_name):
    # chromedriver的路径
    chromedriver = r"C:\Users\xx\Downloads\chromedriver_win32\chromedriver.exe"
    os.environ["webdriver.chrome.driver"] = chromedriver
    # 设置chrome开启的模式,headless就是无界面模式
    # 一定要使用这个模式,不然截不了全页面,只能截到你电脑的高度
    chrome_options = Options()
    chrome_options.add_argument( 'headless' )
    driver = webdriver.Chrome( chromedriver, options=chrome_options )
    # 控制浏览器写入并转到链接
    driver.get( url )
    time.sleep( 1 )
    driver.set_window_size( 1200, 900 )
    # 以下代码是将浏览器页面拉到最下面。
    driver.execute_script( """
            (function () {
                var y = 0;
                var step = 100;
                window.scroll(0, 0);
                function f() {
                    if (y < document.body.scrollHeight) {
                        y += step;
                        window.scroll(0, y);
                        setTimeout(f, 100);
                    } else {
                        window.scroll(0, 0);
                        document.title += "scroll-done";
                    }
                }
                setTimeout(f, 1000);
            })();
        """ )
    # driver.maximize_window()
    time.sleep( 1 )
    # 截图并关掉浏览器
    driver.save_screenshot( pic_name )
    driver.close()
if __name__ == '__main__':
    get_image( 'http://baidu.com', 'image.png' )

PyQt5 网站页面截图

pip install PyQt5

pip install PyQtWebEngine

import sys

from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import Qt, QUrl, QTimer
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineSettings

class Screenshot(QWebEngineView):

    def capture(self, url, output_file):
        self.setWindowState(Qt.WindowFullScreen)
        self.output_file = output_file
        self.load(QUrl(url))
        self.loadFinished.connect(self.on_loaded)
        # Create hidden view without scrollbars
        self.setAttribute(Qt.WA_DontShowOnScreen)
        self.page().settings().setAttribute(
            QWebEngineSettings.ShowScrollBars, False)
        self.show()

    def on_loaded(self):
        size = self.page().contentsSize().toSize()
        self.resize(size)
        # Wait for resize
        QTimer.singleShot(1000, self.take_screenshot)

    def take_screenshot(self):
        self.grab().save(self.output_file, b'PNG')
        self.app.quit()


app = QApplication(sys.argv)
s = Screenshot()
s.app = app
s.capture('http://testing.mshare.cn', 'webpage.png')
sys.exit(app.exec_())

发表评论

邮箱地址不会被公开。 必填项已用*标注