【问题标题】:Select an element by the text it contains with Selenium Webdriver使用 Selenium Webdriver 通过它包含的文本选择一个元素
【发布时间】:2014-09-21 02:05:43
【问题描述】:

我刚开始使用 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”。

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

【问题讨论】:

    标签: c# selenium selenium-webdriver css-selectors


    【解决方案1】:

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

    //button[.='xyz']
    

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

    【讨论】:

    【解决方案2】:

    您可以通过可见文本找到链接。

    IWebElement XyzLink= _browser.FindElement(By.LinkText("xyz"));

    您也可以通过部分链接文本来定位链接,如下所示,

    IWebElement XyzPartialLink= _browser.FindElement(By.PartialLinkText("XYZ"));

    例如,这将定位一个在其文本中包含“XYZ”的链接元素。

    【讨论】:

    • 如果链接包含,比如说,其中包含所需文本的跨度,会发生什么?例如。 MyText
    猜你喜欢
    • 2015-08-19
    • 2012-07-09
    • 2021-10-03
    • 1970-01-01
    • 2017-10-27
    • 2019-06-03
    • 2019-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多