问题
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