AttributeError: 'NoneType' object has no attribute 'text' when inside a function

Question:

I have the below code outside of a function which returns a text value, however the same code in a function returns the next error:

Traceback (most recent call last):
    File "/Users/danielpereira/PycharmProjects/fmoves_scraper/movie_scraper.py", line 14, in <module>
    find_movie(line)
  File "/Users/danielpereira/PycharmProjects/fmoves_scraper/movie_scraper.py", line 9, in find_movie
    resolution = soup.find('span', class_='item mr-3').text
    AttributeError: 'NoneType' object has no attribute 'text'

The contents of the movies.text file are 2 links:

https://fmovies.app/movie/watch-top-gun-maverick-online-5448
https://fmovies.app/movie/watch-thor-love-and-thunder-online-66670

Code:

import requests
from bs4 import BeautifulSoup


def find_movie(url):
    source_code = requests.get(url)
    soup = BeautifulSoup(source_code.content, 'html.parser')
    resolution = soup.find('span', class_='item mr-3').text
    return resolution


with open('movies.txt', 'r') as file:
    for links in file:
        movie_link = find_movie(links)
        print(movie_link)
Asked By: Daniel Pereira

||

Answers:

The code seems to work, I think the problem is in the reading of the urls, try:

import requests
from bs4 import BeautifulSoup

def find_movie(url):
    source_code = requests.get(url)
    soup = BeautifulSoup(source_code.content, "html.parser")
    resolution = soup.find("span", class_="item mr-3").text
    return resolution


with open("movies.txt", "r") as file:
    for links in file.readlines():
        movie_link = find_movie(links.strip())
        print(movie_link)

with output:

HD
CAM
Answered By: itogaston
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.