[英]How can I get text from element with Selenium webdriver and Java?
My code: 我的代码:
WebDriver driver = new SafariDriver();
driver.get("http://bet.hkjc.com/football/default.aspx");
WebElement matchs = driver.findElement(By.cssSelector("span.Head to Head"));
System.out.println(matchs);
driver.quit();
How can I crawl Manchester Utd
and Celta Vigo
? 我如何爬行
Manchester Utd
和 Celta Vigo
?
WebElement matchs = driver.findElement(By.xpath("//a[@title='Head to Head']"));
System.out.println(matchs.getText());
Use firebug
and firepath
addons in firefox
and inspect that element and get the xpath and put it here inside double quotes in this code : 在
firefox
使用firebug
和firepath
插件,检查该元素并获取xpath并将其放在此代码的双引号中:
System.out.println(driver.findElement(By.xpath("")).getText());
If you don't know how to use firebug and firepath refer this link 如果您不知道如何使用Firebug和Firepath,请参考此链接
You can locate the element either by css selector or xpath selector 您可以通过css选择器或xpath选择器找到元素
By using xpath 通过使用xpath
driver.findElement(By.xpath("//a[@title='Head to Head']"));
By using css Selector 通过使用CSS选择器
driver.findElement(By.cssSelector("span > a[title='Head to Head']"));
OR Try somethings like this if not getting the match 或者如果没有找到匹配项,请尝试类似这样的操作
driver.findElement(By.cssSelector("td.cteams.ttgR2>span>a[title='Head to Head']"));
Note : in your code you are trying like span.Head to Head
in CSS selector .
注意:在您的代码中,您尝试使用CSS选择器中的
span.Head to Head
.
dot represents the class and according to your path you are locating span tag which have class name "Head to Head" which doesn't exist in your dom as this is the title of anchor tag. 点代表类,根据您的路径,您将找到具有“ Head to Head”类名称的span标签,该类名称在您的dom中不存在,因为这是锚标签的标题。
Went through the Firebug
and Firepath
plugins of Firefox initially to get the Xpath or css path 最初通过Firefox的
Firebug
和Firepath
插件获得了Xpath或CSS路径
Explore some blogs to get clear understanding, you will be able to create by yourself 探索一些博客以获得清晰的了解,您将可以自己创建
I assume all the above answers doesn't work for you and am providing another answer. 我认为以上所有答案对您都不起作用,并提供了另一个答案。
I can see both the texts are under "a" tag. 我可以看到两个文本都在“ a”标签下。 So the idea is to navigate to the element and use getText() - which returns the visible text.
因此,想法是导航到该元素并使用getText() -返回可见的文本。
String word = driver.findElement(By.xpath("//span/a")).getText();
System.out.println(word);
Hope this works for you. 希望这对您有用。
In all of my tests I'm using the getAttribute like this to get text and it is working fine for me on all drivers : 在我所有的测试中,我都使用类似的getAttribute来获取文本,并且在所有驱动程序上都可以正常工作:
assertEquals(strCity, txtCity.getAttribute("value")); assertEquals(strCity,txtCity.getAttribute(“ value”)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.