Skip to main content
 首页 » 编程设计

python之使用BeautifulSoup,如何防止元素找不到

2025年05月04日20JustinYoung

我正在遍历表格中的表格行,但前 1 或 2 行没有我要查找的元素(它们用于表格列标题等)。

所以在说完第 3 个表格行之后,表格单元格 (td) 中的元素具有我正在寻找的内容。

例如

td[0].a.img['src'] 

但是调用失败,因为前几行没有这个。

How can I guard against these cases so my script doesn't fail? 

我收到如下错误:

nonetype object is unsubscriptable 

请您参考如下方法:

最简单和最清晰的,如果你想让你的代码“在线”:

theimage = td[0].a.img 
if theimage is not None: 
   use(theimage['src']) 

或者,最好将 None 检查包装在您自己的一个小函数中,例如:

def getsrc(image): 
  return None if image is None else image['src'] 

并使用getsrc(td[0].a.img)。