python - XPath 类是和文本包含

标签 python xpath

我在 XPATH 方面一直在慢慢进步,但每次我认为我已经掌握了它(至少在基本水平上)时,一些我认为很明显的东西决定扔掉我。

尝试点击列表项:

<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>

有了这个:

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

我正在仔细检查所有内容是否已实际加载等...并且(根据我对 XPATH 的理解)这应该是在查找列表项。

任何人都可以阐明我所缺少的东西吗?

最佳答案

我很确定您可以责怪文本中的额外空格。要么归一化:

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

或者,使用contains():

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

并且,由于您正在为 class 属性使用 contains,因此您可以删除 league_check 之后的尾随空格。


或者,您可以依赖“联盟 ID”,例如:

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)

关于python - XPath 类是和文本包含,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36722796/

相关文章:

python - 类型错误 : ‘DoesNotExist’ object is not callable

python - Django 中的过滤日期字段

php - 使用PHP XPatch在同一foreach循环中从多个域回显文本

php - 搜索 XML 项目 PHP XPath

python - 为什么 text、innerText、innerHTML 在 selenium 中返回空

python - 使用 XML python 库访问数据

python - 测试多个值存储为列表的字典中是否存在特定的键和值

python - 为什么 `gevent.spawn` 与 monkeypatched `threading.Thread()` 不同?

xml - 选择值小于某个数字的元素

html - 调试 'Error loading stylesheet: XPath parse failure: Name or Nodetype test expected:'