Trying to skip empty tags beautifulsoup AttributeError: 'NoneType' object has no attribute 'text'

Question:

I’m trying to read a page with python and print each element for the ratings. I’ve got a AttributeError: 'NoneType' object has no attribute 'text' error and I don’t understand how to fix it.

Here is my code:

rating = movie.find('td', class_='ratingColumn imdbRating').strong.text
if rating:
    try:
        print(rating)
    except AttributeError:
        print("no rating")
Asked By: xorgus

||

Answers:

You can simply check for "NoneType" before printing .text

rating = movie.find('td', class_='ratingColumn imdbRating').strong

if rating:
    print(rating.text)
else:
    print("no rating")
Answered By: ytung-dev

Simply check None Type as below:

rating = movie.find('td', class_="ratingColumn imdbRating").strong

if rating is not None:
    rating = rating.text
else:
    rating = "No Rating"
Answered By: Prince
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.