简体   繁体   English

Selenium JS如何获取元素的文本

[英]Selenium JS how to get text of an element

I have searched for an answer, and this should be relatively easy but how do I go about grabbing the text from a populated table in a browser?我已经搜索了一个答案,这应该相对容易,但是我如何从浏览器中的填充表格中获取文本?

The "inspect" looks something like this: “检查”看起来像这样:

<tr role="row">
  <th class="component-body-text" colspan="1"role="columnheader">### The Text I want ###</th>

Obviously there is more to the table than this, but I just want to be able to grab that piece of text?显然桌子上还有比这更多的东西,但我只想能够抓住那段文字?

would I do something like我会做类似的事情吗

await driver.findElement(By.className('component-body-text')).getText(); 

because that does not work.因为那行不通。 Or since there are multiple elements in the table should I或者由于表中有多个元素,我应该

const sample = await driver.findElements(By.className('component-body-text')); 
sampleText = sample[0].getText();

I have tried both methods.这两种方法我都试过了。

To extract the text The Text I want you can use either of the following Locator Strategies :要提取文本The Text I want您可以使用以下任一Locator Strategies

  • Using className :使用类名

     await driver.findElement(By.className("component-body-text").getText()
  • Using css :使用css

     await driver.findElement(By.css("tr[role='row'] > th.component-body-text[role='columnheader']").getText()
  • Using xpath :使用xpath

     await driver.findElement(By.xpath("//tr[@role='row']/th[@class='component-body-text' and @role='columnheader']").getText()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM