python - 如何在Python中使用Selenium执行右键单击?

标签 python python-2.7 selenium selenium-webdriver right-click

我想知道是否有人有解决方案如何在 DOM 的任何元素上执行简单的右键单击操作。例如,右键单击“Google 搜索”按钮以选择“页面另存为”选项。 根据我的研究,它涉及到 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
<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9ceaf9eedcfbf3f3fbf0f9fff3f8f9b2fff3f1" rel="noreferrer noopener nofollow">[email protected]</a>/components/driver_component.js:9176)
    at DelayedCommand.prototype.executeInternal_/h (file:///tmp/tmpuIgKVI/extens
ions/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="61071905130817041321060e0e060d04020e05044f020e0c" rel="noreferrer noopener nofollow">[email protected]</a>/components/command_processor.js:10831)
    at DelayedCommand.prototype.executeInternal_ (file:///tmp/tmpuIgKVI/extensio
ns/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="395f415d4b504f5c4b795e56565e555c5a565d5c175a5654" rel="noreferrer noopener nofollow">[email protected]</a>/components/command_processor.js:10836)
    at DelayedCommand.prototype.execute/< (file:///tmp/tmpuIgKVI/extensions/fxdr
<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b3dac5d6c1f3d4dcdcd4dfd6d0dcd7d69dd0dcde" rel="noreferrer noopener nofollow">[email protected]</a>/components/command_processor.js:10778)

我哪里出错了? 附注我的测试环境是Ubuntu 12.04,以防万一也无所谓。

最佳答案

Google 搜索按钮的 id 属性是 gbqfba,而不是 qbqfba(如果您看到我看到的同一个谷歌搜索页面):

btn = br.find_element_by_id('gbqfba')
#                            ^

Google Search button

或者您可以通过文本查找按钮:

br.find_element_by_xpath('.//button[contains(., "Google Search")]')

关于python - 如何在Python中使用Selenium执行右键单击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22127393/

相关文章:

Python处理反向查找

selenium - 如何通过Selenium打开Firefox Developer Edition

python - 修改 statsmodels 图表

python - scikit learn 插补 NaN 以外的值

python - python 中的 Opencv 2.4.3 estimateRigidTransform

python - selenium click() 无法关闭弹出窗口

python - 如何使用selenium查找是否选择了ng-grid行

python - 如何在 Heroku 上使用 Google API 凭据 json?

python - 哈里斯角检测器在不同的旋转

ruby - 删除文件中第二个文件中没有匹配项的行的最快方法是什么?