GVKun编程网logo

使用switch_to_windows()并打印标题的Selenium Webdriver不会打印标题。(switch case 怎么多次用打印输入)

23

在这篇文章中,我们将带领您了解使用switch_to_windows的全貌,包括并打印标题的SeleniumWebdriver不会打印标题。的相关情况。同时,我们还将为您介绍有关JavaSeleniu

在这篇文章中,我们将带领您了解使用switch_to_windows的全貌,包括并打印标题的Selenium Webdriver不会打印标题。的相关情况。同时,我们还将为您介绍有关JavaSelenium Webdriver:修改navigator.webdriver标志以防止selenium检测、org.openqa.selenium.WebDriver.Window的实例源码、python+selenium 使用switch_to_alert 出现的怪异常、selenium - switch_to_alert() - 警告框处理的知识,以帮助您更好地理解这个主题。

本文目录一览:

使用switch_to_windows()并打印标题的Selenium Webdriver不会打印标题。(switch case 怎么多次用打印输入)

使用switch_to_windows()并打印标题的Selenium Webdriver不会打印标题。(switch case 怎么多次用打印输入)

这是代码

for handle in browser.window_handles:    print "Handle = ",handle    browser.switch_to_window(handle);    elem = browser.find_element_by_tag_name("title")    print elem.get_attribute("value")

我得到以下输出

Handle =  {564f8459-dd20-45b8-84bf-97c69f369738}NoneHandle =  {85338322-5e58-4445-8fe3-3e822d5a0caf}None

得到手柄后,我切换到窗口并打印标题。为什么我看不到任何标题。没有标题吗?当我看到页面的html源代码时,我会看到标题标签。

答案1

小编典典

页面标题将不在元素的value属性中title,而是该元素的文本内容。

访问该文本的正确方法是 browser.find_element_by_tag_name("title").text

甚至更简单,只需访问即可browser.title

JavaSelenium Webdriver:修改navigator.webdriver标志以防止selenium检测

JavaSelenium Webdriver:修改navigator.webdriver标志以防止selenium检测

如何解决JavaSelenium Webdriver:修改navigator.webdriver标志以防止selenium检测?

从当前的实现开始,一种理想的访问网页而不被检测到的方法是使用ChromeOptions()该类向以下参数添加几个参数:

排除enable-automation开关的集合 关掉 useAutomationExtension 通过以下实例ChromeOptions

Java示例:

System.setProperty("webdriver.chrome.driver", "C:\\Utility\\browserDrivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
options.setExperimentalOption("useAutomationExtension", false);
WebDriver driver =  new ChromeDriver(options);
driver.get("https://www.google.com/");

Python范例

from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option(''useAutomationExtension'', False)
driver = webdriver.Chrome(options=options, executable_path=r''C:\path\to\chromedriver.exe'')
driver.get("https://www.google.com/")

解决方法

我正在尝试使用selenium和铬在网站中自动化一个非常基本的任务,但是以某种方式网站会检测到铬是由selenium驱动的,并阻止每个请求。我怀疑该网站是否依赖像这样的公开DOM变量https://stackoverflow.com/a/41904453/648236来检测selenium驱动的浏览器。

我的问题是,有没有办法使navigator.webdriver标志为假?我愿意尝试修改后重新尝试编译selenium源,但是似乎无法在存储库中的任何地方找到NavigatorAutomationInformation源https://github.com/SeleniumHQ/selenium

任何帮助深表感谢

PS:我还从https://w3c.github.io/webdriver/#interface尝试了以下操作

Object.defineProperty(navigator,''webdriver'',{
    get: () => false,});

但是它仅在初始页面加载后更新属性。我认为网站会在执行脚本之前检测到变量。

org.openqa.selenium.WebDriver.Window的实例源码

org.openqa.selenium.WebDriver.Window的实例源码

项目:marathonv5    文件:JavaDriverTest.java   
public void windowSetSize() throws Throwable {
    driver = new JavaDriver();
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override public void run() {
            frame.setLocationRelativeto(null);
            frame.setVisible(true);
        }
    });
    Window window = driver.manage().window();
    Dimension actual = window.getSize();
    AssertJUnit.assertNotNull(actual);
    java.awt.Dimension expected = EventQueueWait.call(frame,"getSize");
    AssertJUnit.assertEquals(expected.width,actual.width);
    AssertJUnit.assertEquals(expected.height,actual.height);
    window.setSize(new Dimension(expected.width * 2,expected.height * 2));
    actual = window.getSize();
    AssertJUnit.assertEquals(expected.width * 2,actual.width);
    AssertJUnit.assertEquals(expected.height * 2,actual.height);
}
项目:marathonv5    文件:JavaDriverTest.java   
public void windowSetPosition() throws Throwable {
    driver = new JavaDriver();
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override public void run() {
            frame.setLocationRelativeto(null);
            frame.setVisible(true);
        }
    });
    Window window = driver.manage().window();
    Point actual = window.getPosition();
    AssertJUnit.assertNotNull(actual);
    java.awt.Point expected = EventQueueWait.call(frame,"getLocation");
    AssertJUnit.assertEquals(expected.x,actual.x);
    AssertJUnit.assertEquals(expected.y,actual.y);
    window.setPosition(new Point(expected.x + 10,expected.y + 10));
    actual = window.getPosition();
    AssertJUnit.assertEquals(expected.x + 10,actual.x);
    AssertJUnit.assertEquals(expected.y + 10,actual.y);
}
项目:marathonv5    文件:JavaDriverTest.java   
public void nonFrameDialogWindowUsesNameIfExistsAsTitle() throws Throwable {
    driver = new JavaDriver();
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override public void run() {
            frame.setVisible(true);
            window = new java.awt.Window(frame);
            window.setName("awt-window");
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(new JTextField(80));
            window.setLayout(new BorderLayout());
            window.add(panel,BorderLayout.CENTER);
            window.setSize(640,480);
            window.setLocationRelativeto(frame);
            window.requestFocus();
            window.setVisible(true);
        }
    });
    try {
        Thread.sleep(200);
        AssertJUnit.assertEquals("awt-window",driver.getTitle());
    } finally {
        window.dispose();
    }
}
项目:marathonv5    文件:JavaDriverTest.java   
public void nonFrameDialogWindowUsesClassNameAsTitleOnLastResort() throws Throwable {
    driver = new JavaDriver();
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override public void run() {
            frame.setVisible(true);
            window = new java.awt.Window(frame);
            window.setName(null);
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(new JTextField(80));
            window.setLayout(new BorderLayout());
            window.add(panel,480);
            window.setLocationRelativeto(frame);
            window.requestFocus();
            window.setVisible(true);
        }
    });
    try {
        Thread.sleep(200);
        AssertJUnit.assertEquals("java.awt.Window",driver.getTitle());
    } finally {
        window.dispose();
    }
}
项目:bootstrap    文件:TAbstractSeleniumTest.java   
@SuppressWarnings("unchecked")
@Override
protected void prepareDriver() throws Exception {
    System.clearProperty("test.selenium.remote");
    localDriverClass = WebDriverMock.class.getName();
    remoteDriverClass = WebDriverMock.class.getName();
    scenario = "sc";
    super.prepareDriver();
    mockDriver = Mockito.mock(WebDriverMock.class);
    Mockito.when(mockDriver.getScreenshotAs(ArgumentMatchers.any(OutputType.class)))
            .thenReturn(new File(Thread.currentThread().getContextClassLoader().getResource("log4j2.json").toURI()));
    final Options options = Mockito.mock(Options.class);
    Mockito.when(options.window()).thenReturn(Mockito.mock(Window.class));
    Mockito.when(mockDriver.manage()).thenReturn(options);
    final WebElement webElement = Mockito.mock(WebElement.class);
    Mockito.when(mockDriver.findElement(ArgumentMatchers.any(By.class))).thenReturn(webElement);
    Mockito.when(webElement.isdisplayed()).thenReturn(true);
    this.driver = mockDriver;
}
项目:bootstrap    文件:TAbstractParallelSeleniumTest.java   
@SuppressWarnings("unchecked")
@Override
protected void prepareDriver() throws Exception {
    testName = Mockito.mock(TestName.class);
    Mockito.when(testName.getmethodName()).thenReturn("mockTest");
    System.clearProperty("test.selenium.remote");
    localDriverClass = WebDriverMock.class.getName();
    remoteDriverClass = WebDriverMock.class.getName();
    scenario = "sc";
    super.prepareDriver();
    mockDriver = Mockito.mock(WebDriverMock.class);
    Mockito.when(((WebDriverMock) mockDriver).getScreenshotAs(ArgumentMatchers.any(OutputType.class))).thenReturn(
            new File(Thread.currentThread().getContextClassLoader().getResource("log4j2.json").toURI()));
    final Options options = Mockito.mock(Options.class);
    Mockito.when(options.window()).thenReturn(Mockito.mock(Window.class));
    Mockito.when(mockDriver.manage()).thenReturn(options);
    final WebElement webElement = Mockito.mock(WebElement.class);
    Mockito.when(mockDriver.findElement(ArgumentMatchers.any(By.class))).thenReturn(webElement);
    Mockito.when(webElement.isdisplayed()).thenReturn(true);
    this.driver = mockDriver;
}
项目:bootstrap    文件:TAbstractSequentialSeleniumTest.java   
@SuppressWarnings("unchecked")
@Override
protected void prepareDriver() throws Exception {
    testName = Mockito.mock(TestName.class);
    Mockito.when(testName.getmethodName()).thenReturn("mockTest");
    System.clearProperty("test.selenium.remote");
    localDriverClass = WebDriverMock.class.getName();
    remoteDriverClass = WebDriverMock.class.getName();
    scenario = "sc";
    super.prepareDriver();
    mockDriver = Mockito.mock(WebDriverMock.class);
    Mockito.when(((WebDriverMock) mockDriver).getScreenshotAs(ArgumentMatchers.any(OutputType.class))).thenReturn(
            new File(Thread.currentThread().getContextClassLoader().getResource("log4j2.json").toURI()));
    final Options options = Mockito.mock(Options.class);
    Mockito.when(options.window()).thenReturn(Mockito.mock(Window.class));
    Mockito.when(mockDriver.manage()).thenReturn(options);
    final WebElement webElement = Mockito.mock(WebElement.class);
    Mockito.when(mockDriver.findElement(ArgumentMatchers.any(By.class))).thenReturn(webElement);
    Mockito.when(webElement.isdisplayed()).thenReturn(true);
    this.driver = mockDriver;
}
项目:bootstrap    文件:TAbstractRepeatableSeleniumTest.java   
@SuppressWarnings("unchecked")
@Override
protected void prepareDriver() throws Exception {
    System.clearProperty("test.selenium.remote");
    localDriverClass = WebDriverMock.class.getName();
    remoteDriverClass = WebDriverMock.class.getName();
    scenario = "sc";
    super.prepareDriver();
    mockDriver = Mockito.mock(WebDriverMock.class);
    Mockito.when(mockDriver.getScreenshotAs(ArgumentMatchers.any(OutputType.class))).thenReturn(
            new File(Thread.currentThread().getContextClassLoader().getResource("log4j2.json").toURI()));
    final Options options = Mockito.mock(Options.class);
    Mockito.when(options.window()).thenReturn(Mockito.mock(Window.class));
    Mockito.when(mockDriver.manage()).thenReturn(options);
    final WebElement webElement = Mockito.mock(WebElement.class);
    Mockito.when(mockDriver.findElement(ArgumentMatchers.any(By.class))).thenReturn(webElement);
    Mockito.when(webElement.isdisplayed()).thenReturn(true);
    this.driver = mockDriver;
}
项目:marathonv5    文件:JavaDriverTest.java   
public void windowSize() throws Throwable {
    driver = new JavaDriver();
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override public void run() {
            frame.setLocationRelativeto(null);
            frame.setVisible(true);
        }
    });
    Window window = driver.manage().window();
    Dimension actual = window.getSize();
    AssertJUnit.assertNotNull(actual);
    java.awt.Dimension expected = EventQueueWait.call(frame,actual.height);
}
项目:marathonv5    文件:JavaDriverTest.java   
public void windowPosition() throws Throwable {
    driver = new JavaDriver();
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override public void run() {
            frame.setLocationRelativeto(null);
            frame.setVisible(true);
        }
    });
    Window window = driver.manage().window();
    Point actual = window.getPosition();
    AssertJUnit.assertNotNull(actual);
    java.awt.Point expected = EventQueueWait.call(frame,actual.y);
}
项目:marathonv5    文件:JavaDriverTest.java   
public void windowMaximize() throws Throwable {
    driver = new JavaDriver();
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override public void run() {
            frame.setLocationRelativeto(null);
            frame.setVisible(true);
        }
    });
    Window window = driver.manage().window();
    window.maximize();
}
项目:willtest    文件:DefaultFirefoxConfigurationParticipant.java   
/**
 * Moves window to the first display,and maximizes there.
 * This is practical in case of local testing.
 *
 * @see WebDriverConfigurationParticipant#postconstruct(WebDriver)
 */
@Override
public void postconstruct(D webDriver) {
    Window window = webDriver.manage().window();
    Dimension dimension = new Dimension(1920,1080);
    Point thisPointIsAlwaysOnFirstdisplay = new Point(0,0);
    window.setPosition(thisPointIsAlwaysOnFirstdisplay);
    window.setSize(dimension);
    window.maximize();
}
项目:aet    文件:ResolutionModifier.java   
private void setResolution(WebDriver webDriver) {
  Window window = webDriver.manage().window();
  if (maximize) {
    window.maximize();
    LOG.error("Trying to maximise window to  {}x{}!",window.getSize().getWidth(),window.getSize().getHeight());
  } else {
    LOG.info("Setting resolution to  {}x{}  ",width,height);
    window.setSize(new Dimension(width,height));
  }
}
项目:webtester-core    文件:WebDriverbrowserTest.java   
private Window mockWindow() {
    Options options = mock(Options.class);
    doReturn(options).when(webDriver).manage();
    Window window = mock(Window.class);
    doReturn(window).when(options).window();
    return window;
}
项目:qir    文件:AbstractWebITCase.java   
@Before
public void initData() {
    dataInitService.clear();
    dataInitService.init();
    webDriver = new PhantomJSDriver();
    final Options options = webDriver.manage();
    final Window window = options.window();
    window.setSize(new Dimension(1280,800));
}
项目:webtester-core    文件:WebDriverbrowserTest.java   
@Test
public void testThatMaximizingTheCurrentwindowInvokesCorrectWebDriverMethods() {
    Window window = mockWindow();
    cut.maximizeCurrentwindow();
    verify(window).maximize();
}
项目:fitnesse-selenium-slim    文件:SeleniumFixture.java   
/**
 * <p>
 * <code>
 * | window maximize |
 * </code>
 * </p>
 * Resize currently selected window to take up the entire screen
 *
 * @return the window size after maximizing
 */
public String windowMaximize() {
    return SeleniumFixture.WEB_DRIVER.getWhenAvailable(StringUtils.EMPTY,(driver,parsedLocator) -> {
        Window window = driver.manage().window();
        window.maximize();
        return this.fitnesseMarkup.formatWidthAndHeight(window.getSize().getWidth(),window.getSize().getHeight());
    });
}

python+selenium 使用switch_to_alert 出现的怪异常

python+selenium 使用switch_to_alert 出现的怪异常

''''''

Created on 2014年11月22日


@author : songjin

''''''

from selenium import webdriver


import time

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC

from selenium.webdriver import firefox

from selenium.webdriver.common.keys import Keys






#firefoxdriverpath=os.path.abspath("/Applications/Firefox.app/Contents/MacOS/firefoxdriver")

#os.environ["webdriver.firefox.driver"]=firefoxdriverpath

#driver=webdriver.Firefox(firefoxdriverpath)

#driver=webdriver.Firefox()

driver=webdriver.Firefox()

driver.get("http://www.baidu.com")

#点击打开搜索设置

driver.find_element_by_css_selector("#u1 > a[name=''tj_settingicon'']").click()

driver.find_element_by_css_selector("a.setpref").click()

#点击保存设置

driver.implicitly_wait(10)

#driver.find_element_by_css_selector("div#gxszButton a.prefpanelgo[href=''#'']").click()

driver.find_element_by_link_text("保存设置").click()

time.sleep(2)

#driver.find_element_by_css_selector("div#gxszButton a.prefpanelgo[href=''#'']")

#获取网页上的警告信息

#alert=driver.switch_to_alert().text()

if EC.alert_is_present:

    print("Alert exists")

    alert=driver.switch_to_alert()

    print (alert.text)

    alert.accept()

    print("Alert accepted")

else:

    print("NO alert exists")


''''''

try:

    WebDriverWait(driver,10).until(EC.alert_is_present(), 

                                  ''Timed out waiting for PA creation '' +

                                  ''confirmation popup to appear.'')

    print("0")

    alert=driver.switch_to_alert().text() 

    print("1")  

    text=alert.text()

    print(text)

except TimeoutException:

    print("no alert")


#接收警告信息



#alert.accept()

#print("3")

#得到文本信息并打印


#alert=driver.switch_to_alert()


#print("5")

#取消对话框(如果有的话)

#alert=driver.switch_to_alert()

#alert.dismiss()


#输入值(如果有的话)

#alert=driver.switch_to_alert()

#alert.send_keys("xxx")

''''''

driver.quit()

如果switch_to_alert不工作,最重要的问题就是,有1个以上的浏览器开启,导致alert抓取不到。并且在使用switch_to_alert的时候时间会比较长一些,需要等待一会儿才能完成accept等的工作。

原因是因为多个浏览器开启导致无法准确定位到哪个浏览器上,例如同时开启了两个firefox的浏览器,webdriver就无法定位到要测试的那个浏览器上,也就无法正常的获取到测试的那台浏览器上的alert窗口。



selenium - switch_to_alert() - 警告框处理

selenium - switch_to_alert() - 警告框处理

在WebDriver中处理JavaScript所生成的alert、confirm以及prompt十分简单,具体做法是使用 switch_to.alert 方法定位到 alert/confirm/prompt,然后使用text/accept/dismiss/ send_keys等方法进行操作。

  • text:返回 alert/confirm/prompt 中的文字信息。

  • accept():接受现有警告框。

  • dismiss():解散现有警告框。

  • send_keys(keysToSend):发送文本至警告框。keysToSend:将文本发送至警告框
如下图,百度搜索设置弹出的窗口是不能通过前端工具对其进行定位的,这个时候就可以通过switch_to_alert()方法接受这个弹窗。
技术分享图片
 
技术分享图片
 
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from time import sleep
driver = webdriver.Chrome()
driver.implicitly_wait(10)
driver.get("http://www.baidu.com")
# 鼠标悬停至"设置连接
link = driver.find_element_by_link_text(‘设置‘)
ActionChains(driver).move_to_element(link).perform()
# 打开搜索设置
driver.find_element_by_link_text(‘搜索设置‘).click()
sleep(2)
# 保存设置
driver.find_element_by_class_name(‘prefpanelgo‘).click()
sleep(2)
# 接受警告框
text = driver.switch_to_alert().text
print(text)
sleep(5)
driver.switch_to_alert().accept()
sleep(10)
       
driver.quit()

  

通过switch_to_alert()方法获取当前页面上的警告框,并使用accept()方法接受警告框。

今天关于使用switch_to_windows并打印标题的Selenium Webdriver不会打印标题。的介绍到此结束,谢谢您的阅读,有关JavaSelenium Webdriver:修改navigator.webdriver标志以防止selenium检测、org.openqa.selenium.WebDriver.Window的实例源码、python+selenium 使用switch_to_alert 出现的怪异常、selenium - switch_to_alert() - 警告框处理等更多相关知识的信息可以在本站进行查询。

本文标签: