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>

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the response. Im just curious if this code can be optimise further. As mention here: 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?
I am away now.Shall I comeback later?
Ok, appreciate it! Just for the sake of knowledge

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.