【问题标题】:AttributeError: 'NoneType' object has no attribute 'text' when inside a functionAttributeError: \'NoneType\' 对象在函数内没有属性 \'text\'
【发布时间】:2022-08-18 17:32:23
【问题描述】:

我在返回文本值的函数之外有以下代码,但是函数中的相同代码返回下一个错误:

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\'

movies.text 文件的内容是 2 个链接:

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

代码:

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)
  • edit您的问题包含完整的错误消息。
  • 请阅读How to Ask
  • soup.find(\'span\', class_=\'item mr-3\') 似乎返回了 None
  • 有关调试代码的提示,请参阅 this article。如果您需要更多帮助,请将movies.txt 的内容添加到您的问题中。
  • 根据错误,soup 没有找到任何元素,因此它是None,并且直接在None 上,您正在访问.text 属性。我建议您尝试打印哪个 URL 给出错误,即没有这样的元素

标签: python beautifulsoup


【解决方案1】:

该代码似乎有效,我认为问题在于阅读网址,请尝试:

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)

输出:

HD
CAM

【讨论】:

  • 我正在尝试使用上下文管理器从 txt 文件中读取多个链接,这是它失败并抛出错误的地方,您建议的方法有效。
  • 太棒了,谢谢你的帮助。
猜你喜欢
  • 2019-01-10
  • 1970-01-01
  • 1970-01-01
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
  • 2019-07-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多