获取链接文本 - Selenium、Java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20036485/
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
Get link text - Selenium, Java
提问by usr999
I'm trying to get all links from a web page. Tried to use
我正在尝试从网页中获取所有链接。尝试使用
WebDriver driver = FirefoxDriver();
List<WebDriver> elements = driver.findElements(By.tagName("a"));
,but I get 0 link and I don't understand why, can anybody help me?
,但我得到 0 链接,我不明白为什么,有人可以帮助我吗?
I need to get part from I need url text.
我需要从我需要 url 文本中获取一部分。
UPDATEThank you, I think found what I was looking for:
更新谢谢,我想找到了我要找的东西:
List<WebElement> elements = driver.findElements(By.tagName("a"));
for (int i = 0; i < elements.size(); i++) {
System.out.println(elements.get(i).getAttribute("href"));
}
回答by Petr Mensik
You forgot to call WebDriver#get
in order to access some page.
您忘记打电话WebDriver#get
以访问某个页面。
WebDriver driver = FirefoxDriver();
driver.get("www.google.com");
List<WebElement> elements = driver.findElements(By.tagName("a"));
回答by Kevin Bowersox
In the code provided no website is retrieved. Try accessing a web page and then getting the a
elements. Also trying changing from List<WebDriver>
to List<WebElement>
在提供的代码中,没有检索到网站。尝试访问网页,然后获取a
元素。还尝试从 更改List<WebDriver>
为List<WebElement>
WebDriver driver = FirefoxDriver();
driver.get("http://www.google.com");
List<WebElement> elements = driver.findElements(By.tagName("a"));
See this example: http://www.seleniumhq.org/docs/03_webdriver.jsp#introducing-the-selenium-webdriver-api-by-example
请参阅此示例:http: //www.seleniumhq.org/docs/03_webdriver.jsp#introducing-the-selenium-webdriver-api-by-example
The following example works for me:
以下示例对我有用:
public class SeleniumTest {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
// And now use this to visit Google
driver.get("http://www.google.com");
List<WebElement> elements = driver.findElements(By.tagName("a"));
for (WebElement element : elements) {
System.out.println(element.getText());
}
}
}