将 Selenium WebDriver 与 Python 3.4 结合使用。
我正在编写一个抓取工具,并使用相对于某些非根祖先元素的 XPath 来定位元素,如下所示:
ancestor_element = driver.find_element_by_xpath(ancestor_xpath)
child_element = ancestor_element.find_element_by_xpath(child_xpath)
这按预期工作。但是,我不确定如何通过显式等待调用来执行此相对位置,因为我看到的示例使用以下语法:
child_element = WebDriverWait(driver,10).until(
EC.presence_of_element_located((By.XPATH, child_xpath))
)
它似乎根据页面根计算 XPath,并抛出一个错误,抱怨 XPath 字符串的“.//”开头。
对此有什么建议吗?
有同样的问题并遵循lambda
来自@Ron Norris 评论的示例。但是,文档并不清楚如何找到child_element
相对于ancestor_element
,即使使用时lambda
.
你实际上可以替换driver
in the WebDriverWait
打电话给你的ancestor_element
,明确地仅搜索“下”的内容ancestor_element
(尽管文档字符串声明它必须是WebDriver
,我发现一个WebElement
也有效)。
所以我最终得到了这样的结果:
child_element = WebDriverWait(ancestor_element,10).until(
EC.presence_of_element_located((By.XPATH, child_xpath))
)
如果你想使用lambda
,然后你可以这样做:
child_element = WebDriverWait(ancestor_element,10).until(
lambda x: x.find_element_by_xpath(child_xpath)
)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)