Python Selenium "TypeError: 'WebElement' object is not iterable"

Python Selenium "TypeError: 'WebElement' object is not iterable"

我的代码需要帮助。我将 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".

我知道 elems 的结果是一个 WebElement,但我需要使用 find_element_by_xpath 因为我想要一个特定的 div 而这个 div 没有唯一的 id。我没有找到在(例如)字符串中转换 WebElement 的方法。 你有没有想过另一种方法来获得这个特定的 div 但不使用 find_element_by_xpath? 您还有其他解决问题的方法吗?

for job in elems:

如果注意,编译器会认为elems是一个列表。

但您已将 elems 定义为

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

这将 return WebElement 而不是 WebElement.

的列表

问题说明:

请注意,find_element_by_xpath return 是一个网络元素,而 find_elements_by_xpath return 是一个列表。

修正:(使用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)