python-3.x - 我想右键单击并在新选项卡中使用 selenium 和 python 打开链接
问题描述
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)
推荐阅读
- java - 创建一个构造函数,将参数中的值复制到一个名为 data 的数组中
- java - 需要自定义arraylist值如下
- hdfs - CAP 定理如何应用于 HDFS?
- javascript - JavaScript:导入模块或向“文档”添加功能?
- javascript - javascript中不同类型的执行
- php - 当我 DD 我的请求时,Laravel Form post to url 不显示任何内容
- c# - 在 WPF 上下文菜单中使用 cal:Message.Attach 时出现“未找到目标方法”错误
- sql - 有没有办法从字符串文字中提取时间
- pointers - SAMD21 - 指针取消引用硬故障,调试器显示有效对象
- image-processing - 在图像分类和对象识别中使用 DNN 和 CNN 的优缺点