CHeN
CHeN

Reputation: 23

How to get only text in div Tag except child element by Python selenium?

I want to get a text in the div tag by selenium I want to get a text "APPLE". this is the web site HTML

<div class="detail">
            <div class="fr-view fr-view-article"> APPLE <span style="color:#999999;"> BANANA </span></div>            </div>

So I wrote this code

content = driver.find_element('xpath', '//*[@id="BoardDelForm"]/div/div[1]/div[4]/div').text

xpath for

<div class="fr-view fr-view-article">

then I can see the text APPLE BANANA the child element 'BANANA' is include in the text.

So I wroth with using another xpath

content = driver.find_element('xpath', '//*[@id="BoardDelForm"]/div/div[1]/div[4]/div/text()').text

then this error occured

The result of the xpath expression "//*[@id="BoardDelForm"]/div/div[1]/div[4]/div/text()" is: [object Text]. It should be an element.

how to get a only the text APPLE in this HTML?

Upvotes: 2

Views: 346

Answers (1)

Parolla
Parolla

Reputation: 407

You can try this code to get required text:

div = driver.find_element('css selector', 'div.fr-view-article')
print(driver.execute_script('return arguments[0].firstChild;', div)['textContent'])
# ' APPLE '

Upvotes: 1

Related Questions