【发布时间】:2014-04-21 15:15:10
【问题描述】:
如果浏览器窗口在 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()?但我的浏览器对象没有那个方法。我该怎么做才能独立地将窗口带到前台系统?谢谢
测试系统
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()
不工作
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
【问题讨论】:
-
在点击之前可以尝试
move_to_element()吗? -
@alecxe 但它已经在
EC.element_to_be_clickable行出错了(在我点击它之前),元素是无,我怎么能在不引用它的情况下移动到它?该页面使用了一些ajax调用,我必须等待按钮出现,但只要它在bg中,无论我等待多长时间,它都不会“出现”到webdriver,实际上它出现在浏览器窗口中,我可以看到它。 -
去掉
EC.element_to_be_clickable检查并尝试move_to_element()。 -
@alecxe 你的意思是这样吗?见问题编辑。哦等等如何访问这个 move_to_element() 方法?它不在浏览器对象中。
标签: python firefox selenium xpath webdriver