Selenium C#-如何从锚标记中删除或替换target = _blank

时间:2018-10-02 20:21:23

标签: javascript c# selenium dom selenium-webdriver

我有以下html代码段:

<p>
  <a href="https://www.google.com" target="_blank" onclick="s_objectID="https://www.google.com/_1";return
    <span class>"ms-rteStyle-external-link-small">
       "Production Efficiency Status"
       ::after
    </span>
   </a>
</p>

单击链接后,它将在新选项卡上打开。我想删除target =“ _ blank”或将其替换为target =“ _ self”,以便在同一选项卡上打开链接。

使用Selenium(ChromeDriver),C#和JavaScript,我已完成以下操作:

IJavaScriptExecutor jsX = (IJavaScriptExecutor)Driver.driver;

var elm = Driver.driver.FindElement(By.CssSelector("#WebPartWPQ5 > div.ms-rtestate-field > div > div > p:nth-child(3) > a > span"));

// jsX.ExecuteScript("arguments[0].setAttribute(\"target\", \"_self\")", elm);
jsX.ExecuteScript("arguments[0].removeAttribute(\"target\")", elm);

elm.Click();

上面的代码仍然在新选项卡上打开链接。请指出我需要做的更正,以便在同一标签上打开单击的链接。

我使用了以下参考文献:

  1. https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute
  2. https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute
  3. Selenium - Universal Way to Convert "WebElement" to Javascript or JQuery Object

1 个答案:

答案 0 :(得分:0)

以下代码将从<a>标记中删除“ target”属性:

driver.ExecuteScript("document.getElementsByTagName('a').removeAttribute('target')");