使用Python、Selenium和PhantomJ的现代网页截屏

2024-04-27 18:49:19 发布

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

我试图捕捉一个现代设计网页。以下是我的代码-

def do_screen_capturing(url, screen_path, width, height):
    print("Capturing screen for.. "+url)
    driver = webdriver.PhantomJS()
    driver.set_script_timeout(60)
    if width and height:
        driver.set_window_size(width, height)
    driver.get(url)
    # print(driver)
    driver.execute_script('function whatever(){var a=document.body,b=document.documentElement,c=Math.max(a.scrollHeight,a.offsetHeight,b.clientHeight,b.scrollHeight,b.offsetHeight);window.scrollTo(0,c);var d=Math.max(a.scrollHeight,a.offsetHeight,b.clientHeight,b.scrollHeight,b.offsetHeight);c!=d&&whatever()}whatever();')
    time.sleep(1)
    el = driver.find_element_by_tag_name('body')
    for i in range(1,100,1):
       el.send_keys(Keys.ARROW_DOWN)
    time.sleep(1)
    driver.execute_script('function whatever(){var a=document.body,b=document.documentElement,c=Math.max(a.scrollHeight,a.offsetHeight,b.clientHeight,b.scrollHeight,b.offsetHeight);window.scrollTo(0,c);var d=Math.max(a.scrollHeight,a.offsetHeight,b.clientHeight,b.scrollHeight,b.offsetHeight);c!=d&&whatever()}whatever();')
    time.sleep(1)
    driver.execute_script('window.scrollTo(0, 0);')
    time.sleep(1)
    driver.save_screenshot(screen_path)
    print("Screenshot taken!")
    driver.service.process.send_signal(signal.SIGTERM)
    driver.quit()

当我使用Firefox(在本地机器上)作为驱动程序时,我会得到一个漂亮的屏幕截图。看看使用Firefox作为驱动程序的screenshot。我把截图剪了,因为它太大了。在

问题是当我使用PhantomJS时。似乎它不执行我添加的那些JS脚本。看看使用PhantomJS作为驱动程序的screenshot。在

网站测试-https://www.kitandace.com/ca/en/

有没有办法让PhantomJS的性能与Firefox相似?在


Tags: timevardriverscriptsleepmathphantomjswindow