如何使用机器人框架,硒打开新窗口?

时间:2017-03-20 16:15:46

标签: python selenium selenium-webdriver webdriver robotframework

我的测试页面上有一个链接,默认情况下在新的TAB中打开。我需要打开链接并验证新打开的页面上的一些值。 因为我发现selenium不支持使用标签,所以我试图在新窗口中打开链接,但它仍然无法正常工作.. 我实现了python函数来保存SHIFT键(我之前为CTRL做过这个并且它有效)然后我调用了“click”函数,但链接仍在新标签页中打开

from robot.libraries.BuiltIn import BuiltIn
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains

class CustomSeleniumLibrary(object):
    def __init__(self):
        self.driver = None
        self.library = None
        self.ac = None

    def get_library_instance(self):
        if self.library is None:
            self.library = BuiltIn().get_library_instance('ExtendedSelenium2Library')
        return self.library

    def get_action_chain(self):
        if self.ac is None:
            self.ac = ActionChains(self.get_library_instance()._current_browser())
        return self.ac

def hold_shift(self):
        actionChain = self.get_action_chain()
        actionChain.key_down(Keys.SHIFT)
        actionChain.perform()

机器人关键字是

Open project detail
     wait until element is visible  ${LINK_TO_PROJECT}
     ${project}=  get text  ${LINK_TO_PROJECT}
     hold shift
     click element   ${LINK_TO_PROJECT}
     #sleep  2s
     #release shift
     element should contain   //h3  Project Details: ${project}

我尝试了许多带睡眠的变种,释放了钥匙等,但它从未在新窗口中真正打开链接。我还尝试验证新打开的选项卡中的数据(不尝试在新窗口中打开),但它总是很快重定向到原始选项卡,因此新选项卡上的DOM尚未加载..感谢您的任何建议!

1 个答案:

答案 0 :(得分:1)

您可以使用以下代码处理在新标签页中打开的页面:

$sql = 'SELECT *
    FROM foo
    WHERE as_integer BETWEEN ? AND ?';
$params = [
   // Not sure whether you still need the sprintf('%u') trick in 64-bit PHP
   ip2long('192.168.0.0'), ip2long('192.168.255.255')
];

此外,你可以做一点破解(不推荐,但是......)以避免处理新标签并强制链接在当前标签中打开:

current = driver.current_window_handle
driver.find_element_by_css_selector('a').click() # use own selector
new_tab = [tab for tab in driver.window_handles if tab != current][0]
driver.switch_to.window(new_tab)
# do some actions
driver.close()
driver.switch_to.window(current)