【问题标题】:I want to right click and open link in new tab using selenium with python我想右键单击并在新选项卡中使用 selenium 和 python 打开链接
【发布时间】:2019-02-03 09:14:10
【问题描述】:
from selenium.webdriver import ActionChains

action = ActionChains(driver)

action.context_click(driver.find_element_by_id('id')).perform()

它正在为我做一个右键单击,但无法执行进一步的操作。比如使用 python 在新选项卡中打开链接

【问题讨论】:

  • 能否分享一下html。
  • 它可以是任何 url 以 facebook.com 为例,右键单击该链接并在新选项卡中打开该链接

标签: python-3.x selenium


【解决方案1】:

首先,我们导入我们的包:

import selenium.webdriver as webdriver
import selenium.webdriver.support.ui as ui
from selenium.webdriver.common.keys import Keys
from time import sleep  

让我们开始吧:

browser = webdriver.Firefox()
browser.get('https://www.google.com?q=python#q=python')
first_result = ui.WebDriverWait(browser, 15).until(lambda browser: browser.find_element_by_class_name('rc'))
first_link = first_result.find_element_by_tag_name('a')

# Save the window opener (current window, do not mistaken with tab... not the same)
main_window = browser.current_window_handle

# Open the link in a new tab by sending key strokes on the element
# Use: Keys.CONTROL + Keys.SHIFT + Keys.RETURN to open tab on top of the stack 
first_link.send_keys(Keys.CONTROL + Keys.RETURN)

# Switch tab to the new tab, which we will assume is the next one on the right
browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)

# Put focus on current window which will, in fact, put focus on the current visible tab
browser.switch_to_window(main_window)

# do whatever you have to do on this page, we will just got to sleep for now
sleep(2)

# Close current tab
browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w')

# Put focus on current window which will be the window opener
browser.switch_to_window(main_window)

【讨论】:

  • 感谢您发布此信息!这是唯一对我有用的解决方案!
【解决方案2】:

正如与您讨论的那样。我已尝试使用右键单击选项在 Facebook 上打开一个创建页面作为新窗口。这是代码。希望这对您有所帮助。

driver = webdriver.Chrome('D:/Java/TestChrome/lib/chromedriver.exe')
driver.get("https://www.facebook.com/")
element=driver.find_element_by_xpath("//a[text()[contains(.,'Create a Page')]]")
#Open in new window to click on Create page using right click
ActionChains(driver).context_click(element).key_down(Keys.CONTROL).click(element).perform()

让我知道它是否有效。

【讨论】:

  • 我需要通过右键单击然后打开链接来完成
  • 好的,让我检查一下。
  • 是的,我这样做是右键单击,然后再次使用相同的选择器点击链接。有什么方法可以使用右键单击后出现的弹出窗口打开链接
  • [testingbar.com/… 请看一下这个链接,我想用 python 执行那个
猜你喜欢
  • 2020-09-20
  • 1970-01-01
  • 2016-01-15
  • 1970-01-01
  • 1970-01-01
  • 2013-02-20
  • 1970-01-01
  • 2012-05-07
  • 2019-07-06
相关资源
最近更新 更多