如何在Selenium WebDriver中在新的浏览器选项卡中执行代码

huangapple go评论62阅读模式
英文:

How to execute code in a new browser tab in selenium webdriver

问题

我已经有在Selenium中打开新标签页的代码,使用Python:

class misc_selenium:

    def __init__(self, driver):
        self.driver = driver

    def open_new_tab(self, url, client=None):
        self.driver.execute_script(f'''window.open("{url}", "_blank");''')

但是,在我执行更多的Selenium操作后,它仍然在新标签页中执行。我该如何让Selenium在新打开的标签页中执行?

英文:

I already have code that opens a new tab in selenium, python:

class misc_selenium:

def __init__(self, driver):
    self.driver = driver


def open_new_tab(self, url, client=None):

    self.driver.execute_script(f'''window.open("{url}", "_blank");''')

However after I execute further selenium it still executes it in my new tab. How do I make selenium execute it in the newly opened tab?

答案1

得分: 1

你可以使用以下代码部分进行翻译:

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

切换到新标签页,然后执行以下脚本:

driver.execute_script('navigator.userAgent')
英文:

You can use:

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

to switch to the new tab, and then execute a script:

driver.execute_script('''navigator.userAgent''')

huangapple
  • 本文由 发表于 2023年5月18日 00:02:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76274055.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定