python - Selenium 无法打开新窗口/选项卡
问题描述
我目前正在尝试使用 selenium 抓取网站。我有一个包含元素的表格,我想单击每个元素,在新窗口/选项卡中打开链接,处理此窗口/选项卡,关闭它并单击下一个元素等。到目前为止,我可以单击表,打开链接并处理页面。不幸的是,我无法在新窗口或标签中打开链接。
我无法向元素发送键盘命令。我也试过
action = ActionChains(self.driver)
action.move_to_element(ele)\
.key_down(Keys.SHIFT)\
.click(ele)\
.key_up(Keys.SHIFT)\
.perform()
这以某种方式仅在当前窗口中打开链接(我没有得到新的窗口句柄,仍然只有一个)。如果有任何帮助,我将不胜感激。
编辑:我也无法使用浏览器手动打开新窗口/标签中的链接。
解决方案
要访问 URL,例如https://www.google.co.in
然后单击一个元素,例如作为Gmail的文本链接以在新窗口/标签中打开链接,您可以按照以下解决方案使用类:action_chains
代码块:
from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys options = webdriver.ChromeOptions() options.add_argument("start-maximized") options.add_argument('disable-infobars') driver=webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe') driver.get('https://www.google.co.in') print("Page Title is : %s" %driver.title) mail_link = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "Gmail"))) ActionChains(driver).key_down(Keys.CONTROL).click(mail_link).key_up(Keys.CONTROL).perform()
浏览器快照:
推荐阅读
- java - 使用导航组件而不使用 ViewModel 时如何在后台堆栈中保留 Fragment 实例?
- flutter - 在颤动中对列表进行排序,其中 0 到底部
- mysql - 在 Docker 上的 Mysql 中启用 local-infile
- google-cloud-storage - 如何最好地将 HTML 与字符串一起存储在 Cloud Storage 中
- vue.js - Vue Cli 4.4.6 是否将 ES2020 脚手架到项目中
- javascript - 一旦命令执行者的命令被编辑,机器人如何编辑它的消息?
- powershell - Powershell,无法输入带有一些非 ASCII 字符的哈希表键(在脚本中)
- postgresql - 在 postgres 的模式中查找每个表上的行数
- ms-access - MS Access - 使用 GROUPBY 查询 - 显示具有零值的组
- git - git cmd / github桌面上的所有最新错误