简体   繁体   English

堆栈溢出“TypeError:'WebElement' 对象不可迭代”

[英]Stack overflow "TypeError: 'WebElement' object is not iterable"

I need help with my code.我的代码需要帮助。 For information I use Selenium with python有关信息,我将 Selenium 与 python 一起使用

elems = driver.find_element_by_xpath("//article[@class='page-container']/section/div[3]") 

for job in elems:
    job_list.append(job.get_attribute('href')) 
print(job_list)

The error is错误是

"TypeError: 'WebElement' object is not iterable".

I know that the result of elems is a WebElement, but I need to use find_element_by_xpath because I want a specific div and this div has not an unique id.我知道 elems 的结果是一个 WebElement,但我需要使用 find_element_by_xpath 因为我想要一个特定的 div 而这个 div 没有唯一的 id。 I didn't find a way to convert WebElement in (for example) a string.我没有找到在(例如)字符串中转换 WebElement 的方法。
Do you have any idea of an another way to have this specific div but not using find_element_by_xpath?您是否知道另一种拥有此特定 div 但不使用 find_element_by_xpath 的方法?
Do you have any other idea to skirt the problem ?你有什么其他的想法来解决这个问题吗?

for job in elems:

If you pay attention, the compiler will think elems is a list.如果你注意,编译器会认为 elems 是一个列表。

But you've defined elems as但是你已经将elems定义为

elems = driver.find_element_by_xpath("//article[@class='page-container']/section/div[3]") 

which will return a WebElement not list of WebElement .这将返回一个WebElementWebElement的名单。

Issue Explanation :问题说明:

Note that find_element_by_xpath returns a web element where as find_elements_by_xpath returns a list.请注意, find_element_by_xpath返回一个 web 元素,而find_elements_by_xpath返回一个列表。

Fix : (use find_elements not find_element )修复:(使用find_elements而不是find_element

elems = driver.find_elements_by_xpath("//article[@class='page-container']/section/div[3]") 

for job in elems:
    job_list.append(job.get_attribute('href')) 
print(job_list)

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

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