[英]How to extract text from webdriver elements found through xpath using Selenium and Python
I have working code:我有工作代码:
options_elements = issn_dropdown.find_elements_by_xpath("//ul[contains(@id,'my_id')]//li")
options = [x.text for x in options_elements]
options_elemets
is an array of 5 selenium.webdriver.remote.webelement.WebElement
, each of them contains text
. options_elemets
是一个包含 5 个selenium.webdriver.remote.webelement.WebElement
的数组,每个options_elemets
都包含text
。 The result option
is exactly what I need.结果
option
正是我所需要的。 Why can't I change it to:为什么我不能将其更改为:
options = issn_dropdown.find_elements_by_xpath("//ul[contains(@id,'my_id')]//li/text()")
? ? Test just fails on this line with no particular error displayed.
测试只是在这一行失败,没有显示特定的错误。
text()
in the xpath
returns text node, Selenium doesn't support it. xpath
中的text()
返回文本节点,Selenium 不支持它。 Your first code block is the way to go.你的第一个代码块是要走的路。
You saw it right.你没看错。
find_elements_by_xpath("//ul[contains(@id,'my_id')]//li/text()")
would just fail using Selenium . find_elements_by_xpath("//ul[contains(@id,'my_id')]//li/text()")
使用Selenium只会失败。
We have discussed this functionality in the following discussions我们在以下讨论中讨论了此功能
The WebDriver Specification directly refers to: WebDriver 规范直接指的是:
and none of them precludes a WebElement reference from being a Text Node.并且它们都不排除 WebElement 引用成为文本节点。
So the bottom line was, as the specification does not specify local end APIs.所以底线是,因为规范没有指定本地端 API。 Client bindings are free to choose an idiomatic API that makes sense for their language.
客户端绑定可以自由选择对其语言有意义的惯用 API。 Only the remote end wire protocol is covered here.
此处仅涵盖远程端有线协议。
@Simon Stewart concluded: @西蒙斯图尔特总结道:
One option might be to serialize a Text node found via executing javascript to be treated as if it were an Element node (that is, assign it an ID and refer to it using that).
一种选择可能是将通过执行 javascript 找到的 Text 节点序列化,以将其视为 Element 节点(即为其分配一个 ID 并使用该 ID 引用它)。 Should a user attempt to interact with it in a way that doesn't make sense (sending keyboard input, for example) then an error could be returned.
如果用户尝试以一种没有意义的方式(例如发送键盘输入)与其交互,则可能会返回错误。
Hence, your first option is the way to go:因此,您的第一个选择是要走的路:
options_elements = issn_dropdown.find_elements_by_xpath("//ul[contains(@id,'my_id')]//li")
options = [x.text for x in options_elements]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.