如果浏览器窗口在后台,则此行不起作用。
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()
方法。但我的浏览器对象没有这个方法。我该怎么做才能独立于系统地将窗口置于前台?谢谢。
测试系统:
Python 2.7 Windows 7 x64
Python 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()
无法工作
编辑2:我查看了文档
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.
似乎因为当窗口处于后台或最小化时,元素不可见,所以这个条件永远不会被满足?
不管怎样,我尝试了另一个条件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秒)。
编辑3:奇怪的是,在拥有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
move_to_element()
方法移动到该元素上? - alecxeEC.element_to_be_clickable
行出现错误(在我点击它之前),元素为None,我如何在没有引用的情况下移动到它?页面使用一些ajax调用,我必须等待按钮出现,但只要它在后台,无论我等多久,它都不会“出现”到webdriver中,实际上它出现在浏览器窗口中,我可以看到它。 - ShumanEC.element_to_be_clickable
检查,尝试使用move_to_element()
。 - alecxe