Search code examples
pythonerror-handlingbeautifulsoupattributeerror

BeautifulSoup Error AttributeError: 'NoneType' object has no attribute 'getText'


I am trying to make a program that will scrape a random movie from rotten tomatoes Top 100 Movies Of All Time. Then I want it to print the name of the movie and the Audience Score. I am getting an Attribute Error.

from urllib.request import urlopen
from bs4 import BeautifulSoup 
import random

url = "https://www.rottentomatoes.com/top/bestofrt/"
page = urlopen(url)
soup = BeautifulSoup(page, 'html.parser')
table = soup.find("table",attrs={"class":"table"})
links = table.findAll("a")
titles = []
hyperLinks = []

for link in links:
  titles.append(link.getText().strip())
  hyperLinks.append(link["href"])

choice = random.randint(0,len(hyperLinks) - 1)
page2 = urlopen(url[:-14] + hyperLinks[choice])
soup2 = BeautifulSoup(page2,"html.parser")
span = soup.find("span",attrs={"class":"mop-ratings-wrap__percentage"})
print(titles[choice])
print(span.getText().strip())

The Error is on the last line where I print span.

https://www.rottentomatoes.com/top/bestofrt/


Solution

  • change soup by soup2

    span = soup2.find("span",attrs={"class":"mop-ratings-wrap__percentage"})