我如何从Selenium(Java)中获取文本?

huangapple go评论62阅读模式
英文:

How do I grab text from Selenium (Java)?

问题

I am trying to grab the text $1.00 from the following HTML code (I have the xpath, so don't worry about that). For this purpose, we can say the xpath is //*[@id="price-string"]

$1.00

I have tried using driver.findElement(By.xpath("//[@id="price-string"]")) followed by .gettext(), .getAttribute("textContent"), .getAttribute("innerHTML");

All of them return null, which means they could not find it.

I saw this post here on stackexchange: https://sqa.stackexchange.com/questions/30627/how-to-get-text-under-strong-tag-in-selenium-webdriver-using-java that might help. They say problem is, you cannot directly target/find text nodes with Selenium WebDriver, only regular element nodes. How would you be able to implement a fix in java? Thanks!

英文:

I am trying to grab the text $1.00 from the following HTML code (I have the xpath, so don't worry about that). For this purpose, we can say the xpath is //*[@id="price-string"]

<strong id="price-string">$1.00</strong>

I have tried using driver.findElement(By.xpath("//*[@id="price-string"]")) followed by .gettext(), .getAttribute("textContent"), .getAttribute("innerHTML");

All of them return null, which means they could not find it.

I saw this post here on stackexchange: https://sqa.stackexchange.com/questions/30627/how-to-get-text-under-strong-tag-in-selenium-webdriver-using-java that might help. They say problem is, you cannot directly target/find text nodes with Selenium WebDriver, only regular element nodes. How would you be able to implement a fix in java? Thanks!

答案1

得分: 0

尝试以下代码 -

Thread.sleep(2000);
String word = driver.findElement(By.xpath("//strong[@id='price-string']")).getText();
System.out.println(word);

注意 - 如果这是您要寻找的内容,请将其标记为答案。

英文:

Try below code -

Thread.sleep(2000);
String word = driver.findElement(By.xpath("//strong[@id='price-string']")).getText();
System.out.println(word);

Note - if this is what you are looking for then please mark this as an answer.

答案2

得分: 0

在提取值之前执行等待语句,然后等待页面完全加载。

尝试这样做:

Thread.sleep(5000);
String value = driver.findElement(By.xpath("//strong[@id='price-string']")).getText();
System.out.println(value);
英文:

Do a wait statement before extracting the value and then wait for page fully loaded

Try this:

Thread.sleep(5000);
String value = driver.findElement(By.xpath("//strong[@id='price-string']")).getText();
System.out.println(value);

huangapple
  • 本文由 发表于 2020年7月29日 03:42:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/63141658.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定