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


问题内容

我正在遍历表中的表行,但是前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)