【问题标题】:How to selecting option from right click menu with Selenium如何使用 Selenium 从右键菜单中选择选项
【发布时间】:2020-04-09 05:16:44
【问题描述】:

我使用chrome作为驱动,双击/上下文单击后,提示窗口打开,但驱动程序不会切换到提示窗口。这是我尝试过的...我打开的页面是google.com,搜索,然后尝试右键单击,以便我可以在不同的选项卡中打开结果。提前致谢。

.......
element = driver.find_element_by_class_name("LC20lb")
actionchains = ActionChains(driver)
actionchains.context_click(element).perform()
# Driver needs to switch to the popup from here before it can press the down arrow.
sleep(5)
actionchains.send_keys(Keys.ARROW_DOWN).perform()
sleep(4)
driver.quit()

【问题讨论】:

    标签: python selenium automation webdriver selenium-chromedriver


    【解决方案1】:

    使用 pyautogui,您可以在网页上下文之外按向下箭头。下面将选择 context minu 的第一个选项。试试这个:

    element = driver.find_element_by_class_name("LC20lb")
    actionchains = ActionChains(driver)
    actionchains.context_click(element).perform()
    # Driver needs to switch to the popup from here before it can press the down arrow.
    sleep(5)
    #actionchains.send_keys(Keys.ARROW_DOWN).perform()
    import pyautogui
    pyautogui.press('down')
    pyautogui.press('enter')
    sleep(4)
    driver.quit()
    

    【讨论】:

      【解决方案2】:

      这是我尝试过的。

      .......
      element = driver.find_element_by_class_name("LC20lb")
      actionchains = ActionChains(driver)
      actionchains.context_click(element).perform()
      # Driver needs to switch to the popup from here before it can press the down arrow.
      sleep(5)
      actionchains.send_keys(Keys.ARROW_DOWN).perform()
      sleep(4)
      driver.quit()
      

      在上面的代码中,您可以使用 WindowHandles 在窗口之间导航,然后获取执行这些操作所需的窗口上的驱动程序操作。

      .......
      element = driver.find_element_by_class_name("LC20lb")
      actionchains = ActionChains(driver)
      
      
      window_before = driver.window_handles[0]; --- this is for the first window.
      actionchains.context_click(element).perform()
      window_after = driver.window_handles[1]; --- this is for the second window.
      driver.switch_to.window(window_after); --- switching the driver to the window that the action needs to be performed.
      
      
      actionchains.send_keys(Keys.ARROW_DOWN).perform()
      sleep(4)
      driver.quit()
      

      希望这会有所帮助!!!!

      【讨论】:

        【解决方案3】:

        根据您的描述,它不是弹出窗口......它是上下文菜单。上下文菜单是特定于浏览器的,因此无法使用 Selenium 进行交互。在不借助上下文菜单的情况下,还有其他方法可以做到这一点。例如,您可以获取链接的 href(A 标记),而不是右键单击链接,打开一个新窗口,然后将该窗口导航到您从 href 检索到的 URL。

        【讨论】:

        • 感谢您的评论 JeffC。但是驱动程序不会切换到新窗口吗?我希望驱动程序只打开一个新的 chrome 选项卡/窗口而不切换到它。
        • @AnthonyGachathi 驱动程序不会自动切换到新窗口。你必须通过代码来做到这一点。如果你用谷歌搜索,你会发现很多示例代码。
        猜你喜欢
        • 1970-01-01
        • 2012-07-10
        • 1970-01-01
        • 2011-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多