Java Selenium,如何从链接 WebElement 获取 linkText(锚点)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29796984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Selenium, how to get linkText (anchor) from link WebElement
提问by RichardK
I have a WebElement containing link found by url. I can extract url by:
我有一个包含通过 url 找到的链接的 WebElement。我可以通过以下方式提取网址:
element.getAttribute("href");
But the question is: how to extract it's anchor, I'm trying like this:
但问题是:如何提取它的锚点,我正在尝试这样:
webElement.getAttribute("linkText");
It gives me null value. I'm 100% sure this link has an anchor. Is there any way to get anchor ? It's more complicated, but example simplified code could look like this:
它给了我空值。我 100% 确定这个链接有一个锚点。有什么办法可以得到锚点吗?它更复杂,但示例简化代码可能如下所示:
WebDriver driver = new FirefoxDriver();
driver.get("http://stackoverflow.com/questions/tagged/java");
WebElement link = driver.findElement(By.linkText("Bicycles"));
System.out.println(link.getAttribute("href")); // shows http://bicycles.stackexchange.com/
System.out.println(link.getAttribute("linkText")); // shows null
采纳答案by nalini
Try this:
尝试这个:
System.out.println(link.getText());
回答by ddavison
By "Anchor" I think you mean the text of the link? If so, then you can use .getText()
since an <a>
is a block level element.
通过“锚点”,我认为您的意思是链接的文本?如果是这样,那么您可以使用.getText()
因为 an<a>
是块级元素。
link.getText();
回答by Vipin Pandey
Here you can store your id text:
您可以在这里存储您的 ID 文本:
String text = driver.findElement(By.id("Text")).getText();
System.out.println(text);
回答by Jonas_Hess
If getText() returns an empty String, try the innerHTML attribute:
如果 getText() 返回空字符串,请尝试使用 innerHTML 属性:
String text = element.getAttribute("innerHTML")