Selenium/Python将Webdriver从无头模式切换到窗口模式 [英] Selenium / Python switch webdriver from headless to window mode

查看:787
本文介绍了Selenium/Python将Webdriver从无头模式切换到窗口模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将Chrome webdriver从无头模式切换到窗口模式?

Is there any way to switch Chrome webdriver from headless mode to window mode?

我想到的一件事是将现有的Web驱动程序切换"到无头模式. 另一个想法:用旧的某种状态"创建新的webdriver实例(这次是非无头的),以便可以执行用户操作.我不知道该怎么办,或者是否可能.

One thing that came to my mind is to 'switch' existing web driver to non-headless mode. Another idea: to create new instance of webdriver (this time non-headless) with some sort of 'state' from old one so the user operations can be executed. I don't know how to do or if it is possible though.

import os
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException,

options = webdriver.ChromeOptions()
options.add_argument('headless')
driver = webdriver.Chrome(
    executable_path=os.path.join(os.getcwd(), 'chromedriver'),
    chrome_options=options,
    )
driver.get('https://website.com')
try:
    driver.find_element_by_xpath('//h1').click()
except NoSuchElementException:
    print('You have to click it manually')
    # here I need Chrome browser
    # to be opened so that I can click a link
print('The name of this thing is: ', end='')
print(driver.find_element_by_xpath("//h1[@class='name']").text)

推荐答案

如果需要打开新标签页

driver.execute_script("window.open()")

如果您需要切换到新版本

If you need to switch to this new one

driver.switch_to.window(self.driver.window_handles[1])

然后您获得页面

driver.get('https://website.com')

最后您可以将其关闭(新的)

and the end you can close it (the new one)

driver.close()

然后您回到第一个驱动程序

and you back to the first driver

switch_to.window(driver.window_handles[0])

这篇关于Selenium/Python将Webdriver从无头模式切换到窗口模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆