Ale*_*kov 5 python selenium python-2.7 selenium-webdriver
试图找到一种在特定点的 Web 浏览器窗口中发送左键单击的方法时,我感到很困惑。我正在使用 Seleniumselenium-2.44.0
和 Python 2.7。我的最终目标是能够点击窗口中的某些区域,但现在我只想确保我能够点击。我认为点击链接所在的区域是个好主意,因为这样我就可以验证点击确实发生了(即,我将被带到另一个 html 页面)。
满足所有先决条件,我能够启动浏览器并访问和操作各种网络元素。从我在帮助中找到的内容来看,应该使用move_by_offset方法将鼠标光标移动到某个方向。但是,当我运行代码时,点击不会发生(或者它发生了,但没有点击 url 链接并且没有打开新页面)。我什至无法验证是否发生了点击。例如,在正常浏览器会话中单击注销链接时,会发生注销操作。
...
homeLink = driver.find_element_by_link_text("Home")
homeLink.click() #clicking on the Home button and mouse cursor should? stay here
print homeLink.size, homeLink.location
helpLink = driver.find_element_by_link_text("Help")
print helpLink.size, helpLink.location
action = webdriver.common.action_chains.ActionChains(driver)
action.move_by_offset(150,0) #move 150 pixels to the right to access Help link
action.click()
action.perform()
Run Code Online (Sandbox Code Playgroud)
这是我正在使用的网页中该区域的屏幕截图。
元素的大小和位置打印如下:
{'width': 39, 'height': 16} {'y': 47, 'x': 341}
{'width': 30, 'height': 16} {'y': 47, 'x': 457}
Run Code Online (Sandbox Code Playgroud)
页面后面的 html 代码如下,如果值得一看的话。
<a href="/web/">Home</a>
|
<a href="/web/Account/LogOff">Logout</a>
|
<a href="#" onclick="HelpFile.open();">Help</a>
Run Code Online (Sandbox Code Playgroud)
我知道我可以通过多种方式通过查找元素来访问链接,但是我试图在某个位置执行点击,并且我正在使用链接元素来验证点击是否真的发生了。
如何执行点击?
假设您的页面上没有其他任何事情会干扰点击,那么应该这样做:
homeLink = driver.find_element_by_link_text("Home")
homeLink.click() #clicking on the Home button and mouse cursor should? stay here
print homeLink.size, homeLink.location
helpLink = driver.find_element_by_link_text("Help")
print helpLink.size, helpLink.location
action = webdriver.common.action_chains.ActionChains(driver)
action.move_to_element_with_offset(homeLink, 150, 0) #move 150 pixels to the right to access Help link
action.click()
action.perform()
Run Code Online (Sandbox Code Playgroud)
move_to_element_with_offset
如果您希望鼠标位置相对于某个元素,则应该使用。否则,move_by_offset
相对于前一个鼠标位置移动鼠标。当您使用click
或时move_to_element
,鼠标将放置在元素的中心。(关于这些的Java 文档是明确的。)