如何使用Python检查Xpath是否存在并获取Selenium中的跨度文本

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

但是,出现以下错误

TypeError:“ WebElement”类型的对象没有len()

预先感谢您的任何见解。

为了便于故障排除,下面给出了网站的完整外部HTML框架

 <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>
评论
  • qqgsd
    qqgsd 回复

    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