使用 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/