繁体   English   中英

Selenium / Python TypeError:“ WebElement”对象不可迭代

[英]Selenium / Python TypeError: 'WebElement' object is not iterable

我正在尝试从以下HTML打印和/或写入span标记内的文件文本。 只希望它有一次find_element ,而不是find_elements因为只有一个实例:

<div>
  <span class="test">2</span>
</div>

下面是我正在使用的python代码,它生成“'WebElement'对象不可迭代”错误。

test = driver.find_element_by_xpath("/html/body/div")

for numberText in test:
numberTexts = numberText.find_element_by_class_name("test")

print(numberTexts.txt)

您将通过以下方式获得单个元素(第一个):

driver.find_element_by_xpath("/html/body/div")

这显然是不可迭代的。

对于多个元素,例如要得到一个迭代,请使用:

driver.find_elements_by_xpath("/html/body/div")

注意s之后element

另请参阅文档

单个元素将不可迭代。 尝试使用find_elements_by_xpath(复数元素)。

如果只有一个实例,则只需使用它而无需for循环。

错误非常明显... find_element_by_xpath的返回值是WebElement 您无法迭代WebElement ...

您的示例代码中还有其他几个错误。 您可以将整个代码块重写为:

element = driver.find_element_by_class_name("test")
print(element.text)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM