如何使用 Python 使用 Selenium 获取 <ul> 中的 <li> 元素列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28415029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a list of the <li> elements in an <ul> with Selenium using Python?
提问by kramer65
I'm using Selenium WebDriver using Python for UI tests and I want to check the following HTML:
我正在使用使用 Python 的 Selenium WebDriver 进行 UI 测试,我想检查以下 HTML:
<ul id="myId">
<li>Something here</li>
<li>And here</li>
<li>Even more here</li>
</ul>
From this unordered list I want to loop over the elements and check the text in them. I selected the ul-element by its id
, but I can't find any way to loop over the <li>
-children in Selenium.
从这个无序列表中,我想遍历元素并检查其中的文本。我通过它的 选择了 ul 元素id
,但我找不到任何方法来循环<li>
Selenium 中的-children。
Does anybody know how you can loop over the <li>
-childeren of an unordered list with Selenium (in Python)?
有人知道如何<li>
使用 Selenium(在 Python 中)遍历无序列表的-childeren 吗?
采纳答案by Mark Rowlands
You need to use the .find_elements_by_
method.
您需要使用该.find_elements_by_
方法。
For example,
例如,
html_list = self.driver.find_element_by_id("myId")
items = html_list.find_elements_by_tag_name("li")
for item in items:
text = item.text
print text
回答by German Petrov
You can use list comprehension:
您可以使用列表理解:
# Get text from all elements
text_contents = [el.text for el in driver.find_elements_by_xpath("//ul[@id='myId']/li")]
# Print text
for text in text_contents:
print text