簡體   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