如何使用selenium和PhantomJS在python中打开新选项卡

时间:2016-05-07 18:39:57

标签: python selenium tabs phantomjs

在Python 3.4中设置自动浏览器测试,并使用无头浏览器 - phantomjs。

打开新标签(Keys.CONTROL +'t')的常用方法不适用于phantomjs。我假设我可以使用selenium中的方法,或者phantomjs打开标签的特定组合键,但是我找不到它。我可以使用chrome或firefox,但我只想要PhantomJS。

我需要一个新标签,因为我会打开两个标签,并通过以下方式在窗口之间切换:

handles = driver.window_handles driver.switch_to.window(句柄[0])

phantomjs的问题在于它不会创建新选项卡,因此只能创建一个句柄。

有人知道吗?

1 个答案:

答案 0 :(得分:0)

哇,对此答案迟到了......但要记住的一件事是PhantomJS是一个无头浏览器。没有“标签”,例如您在Firefox,Chrome等中看到的内容。您要做的是打开一个新窗口,只能通过execute_script完成。例如,如果运行以下命令,您将很好地了解窗口在Selenium中的工作方式:

driver = webdriver.PhantomJS()
driver.get("https://linkedin.com")
driver.execute_script("$(window.open('https://twitter.com'))")
print driver.current_window_handle

# Switch to new window
driver.switch_to_window(driver.window_handles[-1])
print " Twitter window should go to facebook "
print "New window ", driver.title
driver.get("http://facebook.com")
print "New window ", driver.title

# Switch to old window
driver.switch_to_window(driver.window_handles[0])
print " Linkedin should go to gmail "
print "Old window ", driver.title
driver.get("http://gmail.com")
print "Old window ", driver.title

# Again new window
driver.switch_to_window(driver.window_handles[1])
print " Facebook window should go to Google "
print "New window ", driver.title
driver.get("http://google.com")
print "New window ", driver.title