Using BeautifulSoup, how to guard against elements not being found?

前端 未结 2 1819
花落未央
花落未央 2021-01-16 09:56

I am looping through table rows in a table, but the first 1 or 2 rows doesn\'t have the elements I am looking for (they are for table column headers etc.).

So after

相关标签:
2条回答
  • 2021-01-16 10:26

    Simplest and clearest, if you want your code "in line":

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

    Or, preferably, wrap the None check in a tiny function of your own, e.g.:

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

    and use getsrc(td[0].a.img).

    0 讨论(0)
  • 2021-01-16 10:35

    Starting from tr:

    for td in tr.findChildren('td'):
        img = td.findChild('img')
        if img:
            src = img.get('src', '')  # return a blank string if there's no src attribute
            if src:
                # do something with src
    
    0 讨论(0)
提交回复
热议问题