Pyramid Seo
Pyramid Seo

Reputation: 1

How to get span text with selenium?

<p id="line1" class=""><span class="bot">So you have short term memory?</span><span id="snipTextIcon" class="yellow" style="opacity: 1;"></span></p>

I wanna get this text: So you have short term memory?

Here is my code :

const {Builder, By, Key, until} = require('./node_modules/selenium-webdriver/index.js');
const {Options} = require('./node_modules/selenium-webdriver/chrome.js');
(async function() {
  let driver;
  try {
    driver = await new Builder()
        .forBrowser('chrome')
        .setChromeOptions(
            new Options().setMobileEmulation({deviceName: 'Nexus 5X'}))
        .build();
    await driver.get('https://www.cleverbot.com/');
    await driver.findElement(By.name('stimulus')).sendKeys('naber', Key.RETURN);

    const waitFind = (locator) => {
        return driver.findElement(async () => {
            await driver.wait(until.elementLocated(locator));
            return driver.findElement(locator);
        });
    }

    let a = await driver.findElement(By.id('line1')).getText();
    console.log(a);
    await waitFind(By.id('line1'), 5000)
    //await waitFind(By.id('snipTextIcon'), 5000);
  } finally {
    await driver && driver.quit();
  }
})().then(_ => console.log('SUCCESS'), err => console.error('ERROR: ' + err));

Output:

PS C:\Users\pyramid\OneDrive\Masaüstü\deneme> node app

DevTools listening on ws://127.0.0.1:52265/devtools/browser/*******

SUCCESS

I didn't find too much documentation on this.

Upvotes: 0

Views: 1021

Answers (1)

KunduK
KunduK

Reputation: 33384

The text element So you have short term memory? is present inside Span tag.Use following xpath to get the text.

driver.findElement(By.xpath('//span[@class="bot"]')).getText()

OR

driver.findElement(By.xpath('//p[@id="line1"]//span[@class="bot"]')).getText()

Upvotes: 2

Related Questions