简体   繁体   中英

BeatuifulSoup parsing logic - check if an image exists before running the code

I'm using scraperapi.com and Bs4 to scrape urls from a website and when it can't find a specfic element it crashes the entire code

the line in question is this one which i'm using to extract the image src

image = soup.find('img')['src']

and I know I need to add a check to see if it exists before scraping it, something like

        return image[src]
    return ''```

but it doesn't seem to work, can anyone advise what i'm doing wrong?

You could simply wrap the code that causes the issue into try and except blocks. That way your code should continue executing.

try:
    image = soup.find('img')['src']
except:
    image = None

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM