使用Selenium单击伪元素

Jan*_*and 10 javascript c# selenium pseudo-element

我正在尝试使用Selenium来点击一个:: after伪元素.我意识到这不能通过WebDriver直接完成,但似乎无法通过Javascript找到一种方法.

这是DOM的样子:

<em class="x-btn-split" unselectable="on" id="ext-gen161">
    <button type="button" id="ext-gen33" class=" x-btn-text">
        <div class="mruIcon"></div>
        <span>Accounts</span>
    </button>
    ::after
</em>
Run Code Online (Sandbox Code Playgroud)

这就是上面的元素.对象的左侧是"按钮"元素,而后面元素是右侧,带有箭头,单击时会显示下拉菜单.正如您所看到的那样,右侧没有任何标识符,这部分是使得这很难做到的.

要点击的元素

我已经在stackoverflow中看到了这两个链接,并试图将答案组合起来形成我的解决方案,但无济于事.

使用JavaScript在Selenium WebDriver中单击元素使用JavaScript在Selenium WebDriver中
查找伪元素

这是我的尝试之一:

string script = "return window.getComputedStyle(document.querySelector('#ext-gen33'),':before')";
IJavaScriptExecutor js = (IJavaScriptExecutor) Session.Driver;
js.ExecuteScript("arguments[0].click(); ", script);
Run Code Online (Sandbox Code Playgroud)

我得到这个错误:

System.InvalidOperationException: 'unknown error: arguments[0].click is not a function
  (Session info: chrome=59.0.3071.115)
  (Driver info: chromedriver=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41),platform=Windows NT 6.1.7601 SP1 x86_64)'
Run Code Online (Sandbox Code Playgroud)

我也尝试使用Selenium中的Actions类来引用鼠标左侧,类似于这个答案.我想这可能是因为我不知道测量的偏移是什么,文档似乎没有给出任何指示.我认为它是以像素为单位?

Actions build = new Actions(Session.Driver);
build.MoveToElement(FindElement(By.Id("ext-gen33"))).MoveByOffset(235, 15).Click().Build().Perform();
Run Code Online (Sandbox Code Playgroud)

这个尝试似乎点击某处,因为它没有给出错误,但我不确定在哪里.

我试图在c#中自动化Salesforce(Service Cloud),如果这有帮助的话.

也许有人可以提供解决方案?

小智 6

我在为Salesforce编写Selenium测试时遇到了同样的问题,并设法通过使用Actions直接控制鼠标来解决它.

这个按钮的包装表具有250px的硬编码宽度,你已经发现了这一点.要找到鼠标的位置,您可以使用contextClick()方法而不是Click().它模拟鼠标右键,这样它将始终打开浏览器菜单.

如果你这样做:

Actions build = new Actions(Session.Driver);
build.MoveToElement(FindElement(By.Id("ext-gen33"))).ContextClick().Build().Perform();
Run Code Online (Sandbox Code Playgroud)

你会发现鼠标移动到WebElement的中间,而不是左上角(我认为它也是如此).由于该元素宽度是常量,我们可以将鼠标移动250 / 2 - 1到右边,它将起作用:)代码:

Actions build = new Actions(Session.Driver);
build.MoveToElement(FindElement(By.Id("ext-gen33"))).MoveByOffset(124, 0).Click().Build().Perform();
Run Code Online (Sandbox Code Playgroud)