python-3.x - 我想右键单击并使用 selenium 和 python 在新选项卡中打开链接

标签 python-3.x selenium

from selenium.webdriver import ActionChains

action = ActionChains(driver)

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

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

最佳答案

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

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)

关于python-3.x - 我想右键单击并使用 selenium 和 python 在新选项卡中打开链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54501445/

相关文章:

python - 如何为 python 3 安装所有 python 2 包?

Python pickling 保持对象身份

python - 如何获取 groupby 总计,然后计算 Pandas DataFrame 列的百分比

python - 如何使用 selenium 从列表中选择一个项目?

java - Selenium 断言文本

python-3.x - 如何从python3中的子文件夹导入模块(带有空的__init__.py)

python-3.x - scikit-learn 的 VotingClassifier 中使用的分类器是什么?

javascript - Selenium python slider bouton 元素不可见异常

python - 使用 Selenium 从表中抓取数据

javascript - 访问从 javascript 函数 webdriver 动态生成的 href