Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
630 views
in Technique[技术] by (71.8m points)

python - Selenium - MoveTargetOutOfBoundsException with Firefox

I'v got problem with function move_to_element on Firefox Webdriver (Chrome, IE works well)

driver = webdriver.Firefox()
driver.get("https://stackoverflow.com")
time.sleep(5)
source_element = driver.find_element_by_xpath('//*[@id="footer"]/div/ul/li[1]/a')
ActionChains(driver).move_to_element(source_element).perform()

I am working with these versions: geckodriver - 0.17.0 // Firefox - 54.0 // selenium - 3.4.3

After running this script, on output shows:

selenium.common.exceptions.MoveTargetOutOfBoundsException: Message: (134.96666717529297, 8682.183013916016) is out of bounds of viewport width (1268) and height (854) 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think the correct answer here got lucky that the element they were looking for happened to be at the bottom of the page and didn't really explain why this occurs in Firefox commonly.

Browsers other than Firefox treat Webdrivers move_to_element action as scroll to part of page with element then hover over it. Firefox seems to have taken a hardline stance that move_to_element is just hover and are waiting for a scroll action to fix this.

For now you have to workaround this bug using javascript as mentioned in previous answer, but I suggest using something like this instead of arbitrarily (well I guess the example was a footer) scrolling to bottom of page and hoping object is still in view.

    def scroll_shim(passed_in_driver, object):
        x = object.location['x']
        y = object.location['y']
        scroll_by_coord = 'window.scrollTo(%s,%s);' % (
            x,
            y
        )
        scroll_nav_out_of_way = 'window.scrollBy(0, -120);'
        passed_in_driver.execute_script(scroll_by_coord)
        passed_in_driver.execute_script(scroll_nav_out_of_way)

Then later

source_element = driver.find_element_by_xpath('//*[@id="footer"]/div/ul/li[1]/a')
if 'firefox' in driver.capabilities['browserName']:
    scroll_shim(driver, source_element)
# scroll_shim is just scrolling it into view, you still need to hover over it to click using an action chain.
actions = ActionChains(driver)
actions.move_to_element(source_element)
actions.click()
actions.perform()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...