python - 如何从 Selenium Python 中的元素列表中获取文本?

标签 python html selenium

考虑以下 HTML 代码。

<div id="tree" style="max-height: 300px; overflow-y: scroll;" class="treeview">
 <ul class="list-group">
  <li class="list-group-item node-tree" data-nodeid="0" style="color:undefined;background-color:undefined;">
   <span class="icon glyphicon"></span>
   <span class="icon node-icon glyphicon glyphicon-unchecked">
   </span>
   Apples
  </li>
  <li class="list-group-item node-tree" data-nodeid="1" style="color:undefined;background-color:undefined;">
   <span class="icon glyphicon"></span>
   <span class="icon node-icon glyphicon glyphicon-unchecked">
   </span>
   Bananas
  </li>
  <li class="list-group-item node-tree" data-nodeid="2" style="color:undefined;background-color:undefined;">
   <span class="icon glyphicon"></span>
   <span class="icon node-icon glyphicon glyphicon-unchecked">
   </span>
   Mangoes
  </li>
  <li class="list-group-item node-tree" data-nodeid="3" style="color:undefined;background-color:undefined;">
   <span class="icon glyphicon"></span>
   <span class="icon node-icon glyphicon glyphicon-unchecked">
   </span>
   Grapes
  </li>
 </ul>
</div>

我尝试使用获取文本“Apples”、“Bananas”、“Mangoes”和“Grapes”

i = 1
m = 2
while i < m:
    css_id = ".list-group-item:nth-child(" + str(i) + ") > .node-icon"
    try:
        fruit_text = driver.find_element(By.CSS_SELECTOR, css_id).text
        print(fruit_text)
        i += 1
        m += 1
    except:
        i += 1

但结果没有打印任何字符串。

有什么办法可以解决这个问题吗?

最佳答案

这应该适合你:

fruits_list = driver.find_elements_by_css_selector('.list-group-item.node-tree')

for fruit in fruits_list:
   print(fruit.text)

只要确保.list-group-item.node-tree这个css选择器应该在网页上指示水果。

关于python - 如何从 Selenium Python 中的元素列表中获取文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58315442/

相关文章:

python - 如何使用 Selenium 将鼠标悬停在多个元素上并通过 Python 提取文本

javascript - Flask 静态进度屏幕

python - cvtColor() 转换为 LAB 颜色空间后的 Numpy 8 位和 32 位图像数据类型

python - 更改 IP 地址 Python Selenium

python - 在 Python 中将列表初始化为特定长度

html - 页面更改时是否可以将客户端状态保存在 iFrame 中?

html - 固定页眉与页内 anchor 重叠

javascript - 将 jquery 事件附加到动态创建的元素(jquery 加载 php 文件)

java - 使用 JUnit 的 Selenium

python - 在 Python 上出现异常时如何将 try/except 与 Selenium Webdriver 一起使用