You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

右键点击链接无法选中菜单元素:Selenium ChromeDriver代码执行异常求助

Fixing "Open in New Tab" with Selenium (C#)

Ah, I get it—your attempt to right-click and select "Open in new tab" isn't working because Selenium can't easily interact with the browser's native context menu. Those menus are part of the browser/OS, not the webpage's DOM, so standard WebDriver commands can't target them. Let's use two reliable alternatives instead:

Solution 1: Use Keyboard Shortcuts (Ctrl+Click/Command+Click)

This simulates the common user action of holding Ctrl (Windows/Linux) or Command (Mac) while clicking a link, which natively opens it in a new tab. Here's the updated code:

// Initialize ChromeDriver
IWebDriver driver = new ChromeDriver();
// Navigate to jQuery demo page
driver.Navigate().GoToUrl("http://jqueryui.com/demos/");

// Locate the "build a theme" link
IWebElement elem = driver.FindElement(By.XPath("//*[@id='content']/p[1]/a[1]"));

// Perform Ctrl+Click (Windows/Linux)
Actions action = new Actions(driver);
action.KeyDown(Keys.Control)
       .Click(elem)
       .KeyUp(Keys.Control)
       .Perform();

// For Mac users, replace Keys.Control with Keys.Command:
// action.KeyDown(Keys.Command).Click(elem).KeyUp(Keys.Command).Perform();

If keyboard shortcuts feel unreliable (e.g., due to browser settings), you can directly use JavaScript to open the link's URL in a new tab. This bypasses context menus entirely:

// Initialize driver and navigate to page
IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("http://jqueryui.com/demos/");

// Locate the link and get its URL
IWebElement elem = driver.FindElement(By.XPath("//*[@id='content']/p[1]/a[1]"));
string linkUrl = elem.GetAttribute("href");

// Use JavaScript to open in new tab
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript($"window.open('{linkUrl}', '_blank');");

Why Your Original Approach Failed

When you right-click to open the context menu, Selenium's WebDriver can't interact with those menu items because they're not part of the webpage. Native UI elements like browser menus require tools like AutoIt or Sikuli, which are overkill for this task. The methods above are far more straightforward and reliable.

Bonus: Switch to the New Tab

If you need to interact with the newly opened tab, add this code to switch focus:

// Get all open window handles
List<string> windowHandles = new List<string>(driver.WindowHandles);
// Switch to the second tab (index 1, since the first is index 0)
driver.SwitchTo().Window(windowHandles[1]);

内容的提问来源于stack exchange,提问作者Burak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 07:04:08