Roskoe
Roskoe

Reputation: 159

selenium python xpath trouble finding element text() on page

I'm trying to verify the text Active: from this example

<div class="details">
    <p class="double">
        <a href="url">Set as default</a>
        <br>
        <a id="modal124434" class="modalAction" href="#">Delete</a>
    </p>
    <span class="bold">TEXT</span>
    : 1234567890 (12/2017)
    <br>
    Active:
    <a class="game" href="#GAME">GAME</a>
</div>

I also need to check TEXT to make sure it's there. I used the following to find TEXT:

foo = b.find_element_by_xpath('//span[contains(text(),"TEXT")]/..')

and when I print(foo.text) I can see all the text from the html example abve. So, I thought I could do something like this:

b.find_element_by_xpath('//span[contains(text(),"TEXT")]/..[contains(text(),"Active:")]/a[text()="GAME"]

but I get a NoSuchElement exception. I've also tried:

b.find_element_by_xpath('//*[contains(text(),"Active")]')

and still got nothing. Any help would be much appreciated.

Upvotes: 3

Views: 1646

Answers (3)

Roskoe
Roskoe

Reputation: 159

Coming back to this I was able to find a way to do what I originally wanted

b.find_element_by_xpath('//span[contains(text(),"TEXT")]/..[contains(.,"Active:")]/a[text()="GAME"]')

it seems like using text() only looks into the first textNode that appears on that web element. but using . looks at all textNodes of that element as well as any textNodes that are attached to any childNode "beneath" the current element.

Upvotes: 1

Ankur Singh
Ankur Singh

Reputation: 1289

You can try this xpath :- //span/following-sibling::text()[2]

driver.find_element_by_xpath("//span/following-sibling::text()[2]").text ;

Upvotes: 1

undetected Selenium
undetected Selenium

Reputation: 193308

To print the element texts TEXT, Active: and GAME you can use the following code blocks :

  • To print TEXT :

    print(b.find_element_by_xpath("//div[@class='details']//span[@class='bold']").get_attribute("innerHTML"))
    
  • To print Active: :

    fullsting = b.find_element_by_xpath("//div[@class='details']").get_attribute("innerHTML")
    part_word = fullsting.split(")")
    words = part_word[1].split("G")
    print(words[0])
    
  • To print GAME :

    print(b.find_element_by_xpath("//div[@class='details']//a[@class='game']").get_attribute("innerHTML"))
    

Upvotes: 1

Related Questions