【问题标题】:How to perform right click using Selenium in python?如何在 python 中使用 Selenium 执行右键单击?
【发布时间】:2014-03-02 12:14:25
【问题描述】:

我想知道是否有人解决了如何对 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
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)

我哪里错了? p.s.我的测试环境是 Ubuntu 12.04,以防万一。

【问题讨论】:

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


    【解决方案1】:

    Google 搜索 按钮的 id 属性是 gbqfba,而不是 qbqfba(如果您看到的是与我看到的相同的 google 搜索页面):

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

    或者你可以通过文本找到按钮:

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

    【讨论】:

    • 感谢 falsetru。它工作完美。现在是时候进行下一步了,如何控制右键执行“另存为页面”?
    • @karolinastamblewska,按p(另存为的快捷键)actionChains.send_keys('p').perform(),现在它会弹出一个保存..对话框。
    • @karolinastamblewska,顺便说一句,您可以使用br.page_source 访问页面的源代码。如果您只想保存页面的源代码,只需将br.page_source保存到文件中即可。
    • 非常感谢,这将再次推进我的项目,这远远超出了谷歌搜索,但报废方法仍然相似;)
    猜你喜欢
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多