PoweredByCoffee PoweredByCoffee - 1 year ago 142
Python Question

XPath Class is and Text Contains

I've been slowly getting better at XPATH but every time I think I have it (at least at a basic level) something which I thought was obvious decides to throw me.

Trying to click a list item:

<li class="league_check " id="lg_chk_br_1_l_22953" onclick="BranchWindow.showLeague(1,22953);"> <img leagueid="22953" src="/i/none_v.gif" width="12" height="12" onclick="BranchWindow.switchLeague(1,22953); cancelBubble(event);">Champions League </li>

With this:

eachleague = "Champions League"
link = Driver.find_elements_by_xpath("//li[contains(@class, 'league_check ') and text() = '%s']" % eachleague)

I'm double checking everything has actually loaded etc... And (to my understanding of XPATH) this should be finding the list item.

Can anyone shed some light on what I'm missing?

Answer Source

I'm pretty sure you can blame the extra space inside the text. Either normalize:

//li[contains(@class, 'league_check ') and normalize-space(.) = '%s']" % eachleague

Or, use contains():

//li[contains(@class, 'league_check ') and contains(., '%s')]" % eachleague

And, since you are using contains for the class attribute, you may remove that trailing space after the league_check.

Alternatively, you may rely on the "league id"s, something like:

leagues = {
    "Champions League": 22953,
    # more leagues
league_id = leagues[eachleague]
link = Driver.find_elements_by_xpath("//li[contains(@class, 'league_check') and img/@leagueid = '%d']" % league_id)