0

I would like to extract the span text located within the class badge pull-right bg-green r-r. However, the class badge pull-right bg-green r-r might not always available. Specifically, I would to set element equal to Hello World whenever the class badge pull-right bg-green r-r is availabble, and equal to No Exist when the class badge pull-right bg-green r-r is unavailable.

By tweaking the code from OP1, the following code was realized to suit with the current need.

if len( self.browser.find_element_by_xpath('.//span[@class = "badge pull-right bg-green m-l-5 m-r-5"]') ) > 0 :  
    element = \
    self.browser.find_elements_by_xpath( './/span[@class = "badge pull-right bg-green m-l-5 m-r-5"]' )[ 0 ].text

However, I got the following error

TypeError: object of type 'WebElement' has no len()

Thanks in advance for any insight.

For easy troubleshooting, the complete outer HTML framework of the website is given below

 <li id="tcl_SiringMenu1_sbmenu" class="has-sub">
        <a href="javascript:;">
         <b class="caret pull-right"></b>
         <i class=" tcl tcl -fw tcl -myr"></i>
         <span>Ruang PeluangGame <span class="badge pull-right bg-gray r-r">Hello World</span> </span>
        </a>

        <ul class="sub-menu" style="display: none;">
            <li id="tcl_SiringMenu1_AmbilDuit">
            <a href="/pguna/ambilduit/permainan.aspx">
            Permainx LODR<span class="badge pull-right bg-green r-r">Hello World</span></a>
            </li>
        </ul>
    </li>
mpx
  • 3,081
  • 2
  • 26
  • 56

1 Answers1

1

Simple fix Use find_elements_by_xpath() instead find_element_by_xpath()

if len( self.browser.find_elements_by_xpath('.//span[@class = "badge pull-right bg-green m-l-5 m-r-5"]') ) > 0 :  
    element =self.browser.find_elements_by_xpath( './/span[@class = "badge pull-right bg-green m-l-5 m-r-5"]' )[ 0 ].text
KunduK
  • 32,888
  • 5
  • 17
  • 41
  • Thanks for the response. Im just curious if this code can be optimise further. As mention here: https://stackoverflow.com/a/53340823/6446053 . see comment by Brian Leishman M. The above approach find the element twice. Hence he proposed to have something like e = driver.find_elements_by_id('blah') if e: e[0].click. However, when I tried to emulate this, there is an error around the if syntax. Maybe u have some thought about this? – mpx Apr 24 '20 at 16:29
  • I am away now.Shall I comeback later? – KunduK Apr 24 '20 at 16:40
  • Ok, appreciate it! Just for the sake of knowledge – mpx Apr 24 '20 at 16:40