如何将selenium浏览器带到前台?

新手上路,请多包涵

如果浏览器窗口在 bg 中,则此行不起作用。

 from selenium import webdriver

from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
# available since 2.4.0
from selenium.webdriver.support.ui import WebDriverWait
# available since 2.26.0
from selenium.webdriver.support import expected_conditions as EC

browser = webdriver.Firefox()
browser.get(someWebPage)

element = WebDriverWait(browser, 10).until(
    EC.element_to_be_clickable((By.XPATH, '//button[contains(., "Watch")]')))

elements = browser.find_elements_by_xpath('//button[contains(., "Watch")]')
if elements:
    print 'find watch button',elements
    elements[0].click()

它出错了

  File "myScript.py", line 1469, in getSignedUrl
    EC.element_to_be_clickable((By.XPATH, '//button[contains(., "Watch")]')))
  File "C:\Python27\lib\site-packages\selenium\webdriver\support\wait.py", line 71, in until
    raise TimeoutException(message)
TimeoutException: Message: ''

但如果我将浏览器窗口留在前面,它不会出错。是因为我不应该使用 EC.element_to_be_clickable 吗?我试着忽略这个错误并继续点击我想要的按钮,但它说如果浏览器窗口在后台,它就找不到按钮。所以我认为我应该做的是在涉及该行之前,将浏览器窗口置于前台?

我看到有人在讨论 switchTo() ?但是我的浏览器对象没有那个方法。我该怎么做才能独立地将窗口带到前端系统?谢谢

测试系统

蟒蛇 2.7 视窗 7 x64

蟒蛇 2.6.6 CentOS 6.4

编辑:我试过了

browser.execute_script("window.focus();")

# commented out EC.element_to_be_clickable as suggested by alecxe
# element = WebDriverWait(browser, 20).until(
#     EC.element_to_be_clickable((By.XPATH, '//button[contains(., "Watch")]')))
print 'sleeping 5'
time.sleep(5)
elements = browser.find_elements_by_xpath('//button[contains(., "Watch")]')

print 'before clicking'

from selenium.webdriver.common.action_chains import ActionChains
hover = ActionChains(browser).move_to_element(elements[0])
hover.perform()

print elements
elements[0].click()

不工作

edit2:我检查了文档

class selenium.webdriver.support.expected_conditions.element_to_be_clickable(locator)[source]

    An Expectation for checking an element is visible and enabled such that you can click it.

似乎是因为当窗口处于 bg 或最小化时,元素不是“可见的”,所以这个条件永远不会满足?不管怎样,我尝试了另一种情况

class selenium.webdriver.support.expected_conditions.presence_of_element_located(locator)[source]

    An expectation for checking that an element is present on the DOM of a page. This does not necessarily mean that the element is visible. locator - used to find the element returns the WebElement once it is located

看来这个工作。以前我尝试完全消除这种情况,但它不起作用可能仅仅是因为我没有“等待”足够长的时间(睡眠 5 秒)。

edit3:奇怪的是,即使浏览器窗口最小化,相同的代码在装有 selenium 2.39 python 2.6.6 firefox 28 centos 6.4 的计算机上也能正常工作。但同样的代码尝试了另外两台机器失败了,浏览器窗口必须最大化并且按钮必须“可见” A. win7 x64 firefox 28 selenium 2.41 python2.7 B. Fedora 20 firefox 28 selenium 2.41 python2.7

原文由 Shuman 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
1 个回答
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题