1

I'm currently working on HMI tests. For one of those tests, i would like to get some text on a page to use it later.

The structure of the HTML code is like so :

<span class="class1">
   The text I want to get
   <span class="class2">
      <span class="class3">1</span>
      <i class="class4">
         ::before
      </i>
   </span>
</span>

The text i would like to get is in the span with class="class1". In order to do that, i have this :

text_i_want = self.driver.find_element_by_css_selector('span.class1').text

The output i have however is The text I want to get\n1. I would like to get rid of this \n1 in my string, and to do that, I used this :

text_i_want = text_i_want.split("\\")[0]

However, the output is still The text I want to get\n1. Plus, here are 2 important points:

  • The argument is "\\", because if there is only one backslash, i get a SyntaxError: EOL while scanning string literal
  • I tried print(repr(text_i_want)) to see if the string i was getting in output was different from what I saw on the console, but it's still the same.

Do you guys know how to solve this ?

Note

I tried the solutions exposed here : Split a string by backslash in python. It didn't work for some reasons ..

MatthiasDec
  • 145
  • 1
  • 11

2 Answers2

2

You can split on "\n". Try:

text_i_want = text_i_want.split("\n")[0]
Nazim Kerimbekov
  • 4,712
  • 8
  • 34
  • 58
Jortega
  • 3,616
  • 1
  • 18
  • 21
  • Thanks, it works. But It won't be the case if there is no 'n' after the backslash. Do you have any idea how to manage this case ? – MatthiasDec Dec 18 '19 at 14:59
  • 1
    @ZoulouDu94 ``` .split("\\") ``` will work for "\". The character "\n" is read by the computer as one character so you will not be able to split the "\" out of the "\n" – Jortega Dec 18 '19 at 15:07
  • 1
    Any time. This could also apply to "\r". See this wiki page for new line values. https://en.wikipedia.org/wiki/Newline – Jortega Dec 18 '19 at 15:12
0

Try Python splitlines() function.

print(driver.find_element_by_css_selector("span.class1").text.splitlines()[0])
KunduK
  • 32,888
  • 5
  • 17
  • 41