[英]selenium error(while taking a screenshot) 'NoneType' object has no attribute 'encode'
[英]AttributeError: 'NoneType' object has no attribute 'encode' error while taking screenshot with headless Chrome using Selenium through Python
我一直试图在 python 中使用 selenium 并在 linux 上运行它。 我已经设置它可以访问网站,但由于我在无头环境中使用它,我想作为屏幕截图,以便我可以看到发生了什么。 当我尝试获取屏幕截图时,我只会收到如下消息:
我的python代码如下:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import os
#Setup Chrome in headless
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--window-size=1920x1080")
#Chrome driver
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("https://www/google.com")
#Capture the screen
driver.save_screenshot("screen.png")
driver.close()
您看到错误的原因背后有点不确定:
AttributeError: 'NoneType' object has no attribute 'encode'
但是,如果您使用的是最新版本的Selenium的python客户端。 Selenium v3.141.0 ,而不是add_argument("--headless")
您需要将headless
属性设置为True
。
我能够通过上述更改和一些小的调整来执行您自己的代码块,如下所示:
代码块:
options = webdriver.ChromeOptions() options.headless = True options.add_argument('window-size=1400,600') options.add_experimental_option("excludeSwitches", ["enable-automation"]) options.add_experimental_option('useAutomationExtension', False) driver = webdriver.Chrome(options=options, executable_path=r'C:\\WebDrivers\\chromedriver.exe') driver.get("https://www/google.com") driver.save_screenshot("screen.png") #Capture the screen driver.quit()
您可以在以下位置找到一些相关的详细讨论:
最近有这个问题
serverless -chrome v1.0.0-53
ChromeDriver 2.41.578700
原因是图像尺寸太大。
所以减少窗口大小,例如到 768x1024
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
...
chrome_options.add_argument('--window-size=768x1024')
如果你正在做整页截图 - 限制高度
width = driver.execute_script('return document.body.parentNode.scrollWidth')
height = driver.execute_script('return document.body.parentNode.scrollHeight')
height = height if height < 10000 else 10000
driver.set_window_size(width, height)
driver.save_screenshot(image_path)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.