在Chrome中使用Selenium查找文字

时间:2015-05-21 17:43:02

标签: selenium xpath selenium-webdriver webdriver

在这种情况下如何获取文本200:

<p style="margin:0"> 
You can get <big class="tooltip">200</big> more</p>

我正在尝试使用:

ReadOnlyCollection<IWebElement> list = _driver.FindElements(By.XPath("//*[contains(@class, 'tooltip')]"));

但无法获取文本,因为.Text属性返回一个空字符串:(

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您正在ClassName()使用Xpath

ReadOnlyCollection<IWebElement> list = _driver.FindElements(By.Xpath("//*[@class=\"tooltip\"]/big"));

但是,在这种情况下我会使用CssSelector,因为css总是优先于xpath

ReadOnlyCollection<IWebElement> list = _driver.FindElements(By.CssSelector("big.tooltip"));

考虑到元素不在任何iframe内,因为它没有抛出任何错误,我假设需要等待。请尝试以下

By byCss = By.CssSelector("big.tooltip");
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement myDynamicElement = wait.Until<IWebElement>((d) =>
{
    return d.FindElement(byCss);
});

var text = myDynamicElement.Text;

看起来元素是隐藏的。所以JavaScript可能是你最好的尝试。

var text = ((IJavaScriptExecutor)driver).ExecuteScript("return document.querySelector('.tooltip_health_limit').innerHTML;") as string;

答案 1 :(得分:0)

找到元素后获取文本:

string text = currentElement.Text;