python - 应该是简单的 XPATH 吗?

标签 python selenium xpath web-scraping

使用 Python 和 Selenium,我尝试单击包含文本的链接。在本例中,假设 14:10,这就是我要查找的 DIV。

<div class="league_check" id="hr_selection_18359391" onclick="HorseRacingBranchWindow.showEvent(18359391);" title="Odds Available">                <span class="race-status">                    <img src="/i/none_v.gif" width="12" height="12" onclick="HorseRacingBranchWindow.toggleSelection(18359391); cancelBubble(event);">                </span>14:10 *            </div>

我一直在观察浏览器手动移动。我知道 DIV 在我的代码触发之前已经加载,但我不知道它到底在做什么。

看起来很简单。我不太擅长 XPATH,但我通常会掌握基础知识。

justtime = "14:10"
links = Driver.find_elements_by_xpath("//div*[contains(.,justtime)")

据我所知,该页面上没有其他链接包含文本 14:10,但是当我循环链接并将其打印出来时,它基本上显示了该页面上的每个链接。

我尝试将其范围缩小到该类名称并包含文本

justtime = "14:10"
links = Driver.find_elements_by_xpath("//div[contains(.,justtime) and (contains(@class, 'league_check'))]")

它根本不返回任何内容。真的很难过,这对我来说根本没有意义。

最佳答案

目前,您的 XPath 未使用 justtime python 变量。相反,它引用子元素 <justtime> <div> 中不存在。形式表达contains(., nonExistentElement)将始终评估为 True ,因为nonExistentElement此处转换为空字符串。这可能是您的初始 XPath 返回的元素多于预期的原因之一。

尝试合并 justtime 中的值通过使用字符串插值将变量添加到 XPath 中,并且不要忘记用引号将值括起来,以便可以将其正确识别为 XPath 文字字符串:

justtime = "14:10"
links = Driver.find_elements_by_xpath("//div[contains(.,'%s')]" % justtime)

关于python - 应该是简单的 XPATH 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35987139/

相关文章:

java - 为什么我的程序的行为仅仅基于 Maven 依赖而改变?

xpath - 如何使用 XPATH 查找名为 *logo* 的图像,或者其中包含带有单词 *logo* 的类?

xml - XPath是否具有最大值?

python - 如何从字符串中删除所有空格

python - 当你在 Python 中为一个术语分配一个新方法时,术语是什么?

python - 元组列表分为两个列表

python selenium chrome webdriver 给我数据;页

selenium - 在 Selenium Webdriver 中,如何在文本后获取输入元素?

python - (python) Youtube-dl 连接错误处理

python - 阻止由 selenium firefox 驱动程序产生的弹出窗口