首页 > 解决方案 > 在硒按钮单击C#中的变量后,如何将复制到剪贴板的字符串分配?

问题描述

我想从 selenium 按钮单击复制字符串。该站点提供了一个类似按钮的 div 标签。如果我单击标签,则会将一个 URL 复制到我的剪贴板。我希望将该 URL 转换为字符串。Selenium 能让这一切成为可能吗?这是一些代码:

using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
...
_driverService = ChromeDriverService.CreateDefaultService();
_driverService.HideCommandPromptWindow = true;

_options = new ChromeOptions();
_options.AddArgument("disable-gpu");
_options.AddArgument(String.Format("user-data-dir={0}", profilePath));
// _options.AddArgument("headless");
// headless cannot usable in WPF... why?

_driver = new ChromeDriver(_driverService, _options);

_driver.Navigate().GoToUrl("The site that provides what I want");
_driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);

var element = _driver.FindElementByXPath("The tag's xpath");
element.Click();
// I think this copy an url probably, or not.
// what should I do from here? to assign that url to a string variable?

标签: c#selenium

解决方案


使用 selenium 创建一个文本区域元素,并粘贴剪贴板的内容。然后从文本区域中提取值。

// After clicking the copy-to-clipboard button

var executor = (IJavaScriptExecutor)driver;

var textarea = (IWebElement)executor.ExecuteScript("document.body.appendChild(document.createElement('textarea'));");

var action = new Actions(driver)
    .MoveToElement(textarea)
    .Click()
    .KeyDown(OpenQA.Selenium.Keys.Control)
    .SendKeys("v")
    .KeyUp(OpenQA.Selenium.Keys.Control);
    
action.Perform();

var url = textarea.GetAttribute("value");

推荐阅读