问题描述
在 Python 3.4 中使用 Selenium WebDriver.
Using Selenium WebDriver with Python 3.4.
我正在编写一个刮刀,并使用 XPath 相对于一些非根祖先元素定位元素,如下所示:
I'm writing a scraper, and locating elements using XPaths relative to some non-root ancestor element, such as below:
ancestor_element = driver.find_element_by_xpath(ancestor_xpath)
child_element = ancestor_element.find_element_by_xpath(child_xpath)
这按预期工作.但是,我不确定如何使用显式等待调用来执行此相对位置,因为我看到的示例使用以下语法:
This works as expected. However, I am unsure how to do this relative location with an explicit wait call, as the examples I have seen use this syntax:
child_element = WebDriverWait(driver,10).until(
EC.presence_of_element_located((By.XPATH, child_xpath))
)
它似乎根据页面根来评估 XPath,并抛出一个错误,抱怨 XPath 字符串的.//"开头.
which appears to evaluate the XPath against the page root, and throws an error complaining about the ".//" beginning of the XPath string.
对此有什么建议吗?
推荐答案
有同样的问题并遵循@Ron Norris 评论中的 lambda
示例.但是,文档并不清楚如何找到相对于 ancestor_element
的 child_element
,即使在使用 lambda
时也是如此.
Had this same question and follow the lambda
example from @Ron Norris's comment. However, the documentation isn't clear about how you can find the child_element
relative to the ancestor_element
, even when using lambda
.
您实际上可以将 WebDriverWait
调用中的 driver
替换为您的 ancestor_element
,以便显式地仅搜索 ancestor_element 下"的内容
(尽管文档字符串声明它必须是 WebDriver
的实例,但我发现 WebElement
也可以使用).
You can actually replace driver
in the WebDriverWait
call with your ancestor_element
, to explicitly only search things "under" the ancestor_element
(even though the docstring states that it has to be an instance of WebDriver
, I found that a WebElement
also works).
所以我结束了类似的事情:
So I wound up with something like:
child_element = WebDriverWait(ancestor_element,10).until(
EC.presence_of_element_located((By.XPATH, child_xpath))
)
如果你想使用 lambda
,你可以这样做:
If you want to use a lambda
, you could then do:
child_element = WebDriverWait(ancestor_element,10).until(
lambda x: x.find_element_by_xpath(child_xpath)
)
这篇关于Selenium 显式等待与相对 XPath 定位器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!