How to selecting option from right click menu with Selenium

微笑、不失礼 提交于 2021-02-11 11:53:19

问题


I'm using chrome as the driver and after double-clicking/context-clicking, the prompt window opens but the driver won't switch to the prompt window. Here is what I have tried... The page I am opening is google.com, search, then trying to right-click so i can open the results in different tabs. Thanks in advance.

.......
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()

回答1:


With pyautogui you can press the down arrow outside of the context of the web page. Below will select the first option of the context minu. Try this:

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:


From what you are describing, it's not a popup... it's a context menu. Context menus are browser specific and therefore cannot be interacted with using Selenium. There are other ways to do this without resorting to the context menu. For instance, instead of right-clicking a link you can get the href of the link (A tag), open a new window, and navigate that window to the URL you retrieved from the href.




回答3:


Here is what I have tried.

.......
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()

In the above code you can use WindowHandles to navigate between the window and then get the driver actions on the window that you need to perform the actions.

.......
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()

Hope this helps !!!!



来源:https://stackoverflow.com/questions/59361764/how-to-selecting-option-from-right-click-menu-with-selenium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!