c# - 通过 Selenium Webdriver 包含的文本选择一个元素

标签 c# selenium selenium-webdriver css-selectors

我刚开始使用 Selenium Webdriver,我立即遇到了一个问题,涉及我尝试选择/单击的按钮都没有 ID 并且共享相同的类。

所以我想知道如何根据它们包含的独特文本来选择它们。

我想也许可以使用 css 选择器,但我不确定如何告诉它查找特定文本来选择元素。

我目前拥有的是:

using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium.Internal;

namespace SeleniumTest1.Methods
{
    public class HomePage
    {

        private readonly IWebDriver _browser;
        public HomePage(IWebDriver browser)
        {
            _browser = browser;
        }

        public IWebElement SearchBox()
        {
            return _browser.FindElement(By.Id("searchBox"));
        }

        public void ImageButton()
        {
            _browser.FindElement(By.CssSelector("a")).Click();
        }

    }
}

到目前为止非常基础。

在我有 CssSelector 的地方我不确定是否有选择包含文本“xyz”的“a”。

我试过搜索方法但找不到任何东西,虽然我觉得这一定是以前提出的问题,谢谢。

最佳答案

如果你使用 xpath 就相当容易了。 如果它有独特的文本,你的 xpath 应该看起来像这样

//button[.='xyz']

所以,这里是“.”指向 HTML 层次结构中的父级并仅查找文本

关于c# - 通过 Selenium Webdriver 包含的文本选择一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25019752/

相关文章:

c# - 如何检查页面是否加载了 Selenium

django - chromedriver.quit()之后的多个Chrome处理

c# - 由于语言要求,如何在单独的线程上打开表单

c# - 我可以为 Dictionary<TKey, TValue> 条目使用集合初始值设定项吗?

python - 如何使用selenium从网页中提取数据更加稳健和高效?

java - 在同一台机器上运行 selenium grid hub 和 node

testing - 期望一个元素有一个滚动

java - Selenium click方法统一

c# - 为什么 GroupJoin 不是左外连接?

c# - 使用 CryptoStream (DESCryptoServiceProvider) 解密时如何返回 byte[]