【问题标题】:Python Selenium "TypeError: 'WebElement' object is not iterable" [duplicate]Python Selenium“TypeError:'WebElement'对象不可迭代”[重复]
【发布时间】:2021-12-07 08:45:14
【问题描述】:

我的代码需要帮助。我在 python 中使用 Selenium

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? 你有什么其他的想法来解决这个问题吗?

【问题讨论】:

  • xpath 只返回一个元素,似乎没有这样的元素,所以我猜它返回一个 web 元素

标签: python html selenium url typeerror


【解决方案1】:
for job in elems:

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

但您已将elems 定义为

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

这将返回一个 WebElement 而不是 WebElement 的列表。

问题说明:

请注意,find_element_by_xpath 返回一个 Web 元素,而 find_elements_by_xpath 返回一个列表。

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

【讨论】:

  • 非常感谢!它有帮助!我的代码没有更多错误,但 job_list 的结果是 None,但它与这个问题无关 :)
猜你喜欢
  • 1970-01-01
  • 2022-12-12
  • 2021-10-25
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 2020-11-09
  • 2015-10-23
  • 2018-11-26
相关资源
最近更新 更多