[英]Selenium / Python TypeError: 'WebElement' object is not iterable
I'm trying to print and/or write to file text inside a span tag from the following HTML. 我正在尝试从以下HTML打印和/或写入span标记内的文件文本。 Only want it to
find_element
once, not find_elements
since there's only one instance: 只希望它有一次
find_element
,而不是find_elements
因为只有一个实例:
<div>
<span class="test">2</span>
</div>
Below is the python code I'm using that is generating the "'WebElement' object is not iterable" error. 下面是我正在使用的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)
You're getting a single element (first one) by: 您将通过以下方式获得单个元素(第一个):
driver.find_element_by_xpath("/html/body/div")
which is obviously not iterable. 这显然是不可迭代的。
For multiple elements ie to get an iterable, use: 对于多个元素,例如要得到一个迭代,请使用:
driver.find_elements_by_xpath("/html/body/div")
Note the s
after element
. 注意
s
之后element
。
Also check out the documentation . 另请参阅文档 。
single element will not be iterable. 单个元素将不可迭代。 Try find_elements_by_xpath (pluralize element).
尝试使用find_elements_by_xpath(复数元素)。
If there is only one instance, then simply use it without the for loop. 如果只有一个实例,则只需使用它而无需for循环。
the error is pretty clear... the return value of find_element_by_xpath
is a WebElement
. 错误非常明显...
find_element_by_xpath
的返回值是WebElement
。 You can't iterate a WebElement
... 您无法迭代
WebElement
...
you have several other mistakes in your example code. 您的示例代码中还有其他几个错误。 You could rewrite the entire block of code as:
您可以将整个代码块重写为:
element = driver.find_element_by_class_name("test")
print(element.text)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.