首页 > 解决方案 > 在 Selenium 中单击图像映射

问题描述

我必须测试一个具有巨大图像的应用程序,但只有一小部分可以通过图像映射单击。

我已经尝试了一切来计算正确的位置并点击,但是点击在位置之外并且测试失败。

有人可以告诉我如何记录当前鼠标位置或如何在测试期间显示鼠标吗?

我正在使用动作链将鼠标光标移动到图像的中心,但是从那里我的所有计算都在图像映射矩形之外进行了单击。

请看下面我的代码片段:

        el=driver.find_elements_by_xpath("/html/body/form/table/tbody/tr/td/img")[0]
        #el=driver.find_elements_by_xpath("//html/body/map/area[2]")[0]
        width=el.size["width"]
        height=el.size["height"]        

        action = webdriver.common.action_chains.ActionChains(driver)
        action.move_to_element(el)
        print driver.get_window_position()
        action.move_by_offset(193, 310)
        print driver.get_window_position()
        action.click()
        action.perform()

谢谢,

标签: pythonseleniumgeckodriver

解决方案


只是作为参考。我最终找到了解决方案。

# Wait for the map to show up and navigate to account page
try:
    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "Map")))
except Exception, e:
    print "Image with token toot long to load..."
    raise AssertionError()

href = driver.find_element_by_xpath("//html/body/map/area[2]").get_attribute("href")
driver.get(href)

我可以看到单击只会触发对 HREF 的获取,因此我没有费力地找到确切的单击位置,而是将 href 放在 var 上,然后对该 href 进行获取。

脚本运行良好,甚至更好,它不依赖于屏幕分辨率。


推荐阅读