[英]How to open Previously copy link in the new tab in selenium C#?
Suppose you copy a link by clicking on the button and you want to open that copied link in a new tab, then how to perform this operation in selenium C#.假设你通过点击按钮复制了一个链接,你想在新标签页中打开那个复制的链接,那么如何在selenium C#中执行这个操作。
driver.FindElement(By.Id("button")).click(); -----from this operation we just copy the link.
Question: Now How to open this copy link in new tab?问题:现在如何在新标签页中打开这个复制链接?
After getting the URL link with code like this:使用如下代码获取 URL 链接后:
var url = driver.FindElement(By.Id("button")).Text;
You can open a new tab and switch to it with您可以打开一个新标签并切换到它
((IJavaScriptExecutor)driver).ExecuteScript("window.open();");
driver.SwitchTo().Window(driver.WindowHandles.Last());
And then open the previously saved url there with driver with然后用驱动打开之前保存的url
driver.Url = url;
So that the entire code could be something like this:这样整个代码可能是这样的:
var url = driver.FindElement(By.Id("button")).Text;
((IJavaScriptExecutor)driver).ExecuteScript("window.open();");
driver.SwitchTo().Window(driver.WindowHandles.Last());
driver.Url = url;
In case you are getting the URL by clicking on that element as you mentioned driver.FindElement(By.Id("button")).click();
如果您通过单击提到的元素获得
driver.FindElement(By.Id("button")).click();
so that the URL is copied into the clipboard, you can use code like this:以便将 URL 复制到剪贴板中,您可以使用如下代码:
using System.Windows.Forms;
driver.FindElement(By.Id("button")).click();
string url = Clipboard.GetText()
((IJavaScriptExecutor)_chromeDriver).ExecuteScript("window.open('" + url +"');");
Copied link will be present in the clipboard, and once you've opened a new tab using this:复制的链接将出现在剪贴板中,一旦您使用此打开新选项卡:
driver.SwitchTo().NewWindow(WindowType.Tab);
You could just do this:你可以这样做:
driver.Navigate().GoToUrl(Clipboard.GetText());
if you are facing如果你面对
The name 'Clipboard' does not exist in the current context
after that line of code, you would have to import:在该行代码之后,您将必须导入:
using System.Windows.Forms;
This also could result in below fault:这也可能导致以下故障:
The type or namespace name 'Forms' does not exist in the namespace 'System.Windows' (are you missing an assembly reference?
for that you'll have to go inside your project directory and then go to the project file and add为此,您必须在项目目录中添加 go,然后在项目文件中添加 go 并添加
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<UseWPF>true</UseWPF>
<UseWindowsForms>true</UseWindowsForms>
</PropertyGroup>
this should solve the issue.这应该可以解决问题。
#Approach 2: #方法二:
((IJavaScriptExecutor)driver).ExecuteScript("navigator.clipboard.readText().then(text => window.location.replace(text));");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.