可以打开/显示/渲染无头Selenium会话吗?

人气:452 发布:2022-10-16 标签: python selenium headless browser-automation

问题描述

我知道这与无头自动化的目的背道而驰,但是...

I know this is sort of counter to the purpose of headless automation, but...

我已经在无头模式下使用Selenium和Chromedriver运行了自动化测试.我宁愿让它毫无头绪地运行,但是有时候,它会遇到一个错误,确实需要查看并与之交互.是否可以渲染无头会话并与之交互?也许通过将无头浏览器复制到非无头浏览器中?我可以通过远程调试进行连接,但是开发工具似乎不允许我查看渲染的页面或与任何东西进行交互.

I've got an automation test running using Selenium and Chromedriver in headless mode. I'd prefer to keep it running headless, but occasionally, it runs into an error that really needs to be looked at and interacted with. Is it possible to render and interact with a headless session? Maybe by duplicating the headless browser in a non-headless one? I can connect through remote-debugging, but the Dev Tools doesn't seem to do allow me to view the rendered page or interact with anything.

我可以拍摄屏幕快照,这有什么帮助.但是我真的在寻找交互的能力-有些拖放元素无法与Selenium很好地配合,偶尔会引起问题.

I am able to take screenshots, which sort of helps. But I'm really looking for the ability to interact--there's some drag-and-drop elements that aren't working well with Selenium that are causing issues occasionally.

推荐答案

实际上,这是可能的.

您可以使用ChromeOptions中的"--remote-debugging-port"参数来窥视无头浏览器.例如,

You can peek into a headless browser by using the "--remote-debugging-port" argument in ChromeOptions. For example,

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--remote-debugging-port=9222') # Recommended is 9222
driver = webdriver.Chrome(options=chrome_options)

然后,当Selenium运行时,您可以在常规浏览器中转到 http://localhost:9222 进行查看无头的会议.它将显示指向Chrome打开的每个标签的链接,您可以通过单击链接来查看/交互每个页面.从那里,您可以在Selenium运行其自动化测试时监视Selenium/Chrome.

Then while Selenium is running, you can go to http://localhost:9222 in your regular browser to view the headless session. It will display links to each tab Chrome has open, and you can view/interact with each page by clicking on the links. From there, you'll be able to monitor Selenium/Chrome as Selenium runs its automation test.

791