0

newbie here trying to learn Selenium. I have the following HTML Code:

<div class="lower-text">
<div data-text="winScreen.yourCodeIs">Your Code Is:</div>
<div>OUTPUTCODE</div>
</div>

I am trying to only print the text OUTPUTCODE, however the following code only prints "Your Code Is:".

text = browser.find_elements_by_class_name('lower-text') for test in text: print(test.text)

Any help would be appreciated. Thank you.

immaeetu
  • 3
  • 2

4 Answers4

0

Try the below xpath.

//div[@class='lower-text']/div[last()]

You code should be

print(driver.find_element_by_xpath("//div[@class='lower-text']/div[last()]").text)
supputuri
  • 13,644
  • 2
  • 21
  • 39
  • This unfortunately prints a blank line. – immaeetu Mar 27 '20 at 02:33
  • check if the div is wrapped in an iframe. If that's case then you have to switch to the frame using `driver.switch_to.frame` and then run the line from my answer. – supputuri Mar 27 '20 at 02:35
  • If you want help in checking if the element is wrapped in iframe just try `//div[@class='lower-text']/div[last()]/ancestor::html` [xpath in dev tools](https://stackoverflow.com/questions/55870609/is-there-a-way-to-learn-xpath-without-using-firebug-or-xpath-as-firefox-is-not-s/55870909#55870909) – supputuri Mar 27 '20 at 02:37
0

Try below Solutions:

1. Xpath :

//div[@class='gs_copied']

2. CSS selector

.lower-text > div:nth-child(2)

Your site is unstable and not always generating coupon code.Currently I am getting below error(check screenshot). So wont able to identify elements which i have mentioned above.

You need to amend your logic based on functionality and if person is Unlucky for getting coupon code then you have to write script to handle other functionality based on your site, (e.g: Check out our Hot Deals Page)

enter image description here

SeleniumUser
  • 4,065
  • 2
  • 7
  • 30
0

Try the following approach:

text = driver.find_element_by_xpath("//div[text()='Your Code Is:']//following-sibling::div[text()]").get_attribute('innerHTML')
print(text)
frianH
  • 7,295
  • 6
  • 20
  • 45
0

I have copy pasted your html part in a new text file and tried the following xpath which work perfectly:

//div[@class='lower-text']/div[text()='Your Code Is:']/following-sibling::div

Attaching screenshot link also. Please have a look and hopefully it will solve your problem. https://i.stack.imgur.com/cLLvl.jpg

Saurabh
  • 301
  • 2
  • 3