如何在Python中使用Selenium执行右键点击?
我想知道有没有人能提供一个解决方案,教我如何在网页的任何元素上执行简单的右键点击操作。比如说,我们想在“谷歌搜索”按钮上右键点击,然后选择“另存为”这个选项。
根据我的研究,这个操作需要用到 ActionChains。大致上我的代码是这样的:
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver import ActionChains
br = webdriver.Firefox()
br.get('http://www.google.com')
btn=br.find_element_by_id('qbqfba')
actionChains = ActionChains(br)
actionChains.context_click(btn).perform()
但是出现了以下错误:
File "/usr/local/lib/python2.7/dist-packages/selenium-2.39.0-py2.7.egg/seleniu
m/webdriver/remote/errorhandler.py", line 164, in check_response
raise exception_class(message, screen, stacktrace)
MoveTargetOutOfBoundsException: Message: u'Offset within element cannot be scrol
led into view: (50, 14.5): [object XrayWrapper [object HTMLButtonElement]]' ; St
acktrace:
at FirefoxDriver.prototype.mouseMove (file:///tmp/tmpuIgKVI/extensions/fxdri
ver@googlecode.com/components/driver_component.js:9176)
at DelayedCommand.prototype.executeInternal_/h (file:///tmp/tmpuIgKVI/extens
ions/fxdriver@googlecode.com/components/command_processor.js:10831)
at DelayedCommand.prototype.executeInternal_ (file:///tmp/tmpuIgKVI/extensio
ns/fxdriver@googlecode.com/components/command_processor.js:10836)
at DelayedCommand.prototype.execute/< (file:///tmp/tmpuIgKVI/extensions/fxdr
iver@googlecode.com/components/command_processor.js:10778)
我哪里出错了呢?
顺便说一下,我的测试环境是 Ubuntu 12.04,不知道这是否有影响。
1 个回答
2
谷歌搜索按钮的 id
属性是 gbqfba
,而不是 qbqfba
(如果你看到的谷歌搜索页面和我看到的是一样的):
btn = br.find_element_by_id('gbqfba')
# ^
另外,你也可以通过按钮的文字来找到这个按钮:
br.find_element_by_xpath('.//button[contains(., "Google Search")]')