Nonetype object has no attribute text ошибка

Как personality13 правильно заметил, автор не заметил что в cols[0].td не нужно .td вызывать, т.к. в cols[0] уже находится тег td.

Я приведу полный работающий пример с небольшими своими правками:

from bs4 import BeautifulSoup


def parse(html):
    teams = []
    soup = BeautifulSoup(html)

    for row in soup.select('tbody > tr'):
        cols = row.select('td')

        teams.append({
            'Место': cols[0].text,
            'Команда': [name.text for name in row.select('a[class=name]')],
            'Матчи': cols[2].text
        })

    return teams


if __name__ == '__main__':
    url = 'https://www.sports.ru/epl/table/'

    import urllib.request
    with urllib.request.urlopen(url) as rs:
        html = rs.read()

    teams = parse(html)

    for team in teams:
        print(team)

Консоль:

{'Место': '1', 'Команда': ['Манчестер Юнайтед'], 'Матчи': '3'}
{'Место': '2', 'Команда': ['Ливерпуль'], 'Матчи': '3'}
{'Место': '3', 'Команда': ['Хаддерсфилд'], 'Матчи': '3'}
{'Место': '4', 'Команда': ['Манчестер Сити'], 'Матчи': '3'}
{'Место': '5', 'Команда': ['Вест Бромвич'], 'Матчи': '3'}
{'Место': '6', 'Команда': ['Челси'], 'Матчи': '3'}
{'Место': '7', 'Команда': ['Уотфорд'], 'Матчи': '3'}
{'Место': '8', 'Команда': ['Саутгемптон'], 'Матчи': '3'}
{'Место': '9', 'Команда': ['Тоттенхэм'], 'Матчи': '3'}
{'Место': '10', 'Команда': ['Бернли'], 'Матчи': '3'}
{'Место': '11', 'Команда': ['Сток Сити'], 'Матчи': '3'}
{'Место': '12', 'Команда': ['Эвертон'], 'Матчи': '3'}
{'Место': '13', 'Команда': ['Суонси'], 'Матчи': '3'}
{'Место': '14', 'Команда': ['Ньюкасл'], 'Матчи': '3'}
{'Место': '15', 'Команда': ['Лестер'], 'Матчи': '3'}
{'Место': '16', 'Команда': ['Арсенал'], 'Матчи': '3'}
{'Место': '17', 'Команда': ['Брайтон'], 'Матчи': '3'}
{'Место': '18', 'Команда': ['Борнмут'], 'Матчи': '3'}
{'Место': '19', 'Команда': ['Кристал Пэлас'], 'Матчи': '3'}
{'Место': '20', 'Команда': ['Вест Хэм'], 'Матчи': '3'}

AttributeError: 'NoneType' Object Has No Attribute 'Text' in Python

This error happens when you try to call a method from an object that is None or not initiated. Before calling a method, you need to check if the object is None or not to eliminate this error; after that, call the desired method.

AttributeError is an exception you get while you call the attribute, but it is not supported or present in the class definition.

Causes and Solutions of the AttributeError: 'NoneType' object has no attribute 'text' in Python

This error is common while you’re doing web scraping or XML parsing. During the parsing, you’ll get this error if you get unstructured data.

Here are some more reasons:

  1. Data that JavaScript dynamically rendered.
  2. Scraping multiple pages with the same data.
  3. While parsing XML, if the node you are searching is not present.

Here are the common solutions you can try to get rid of the error:

  1. Check if the element exists before calling any attribute of it.
  2. Check the response to the request.

an Example Code

As this error often comes from web scraping, let’s see an example of web scraping. We will try to get the title of the StackOverflow website with our Python script.

Here is the code:

from bs4 import BeautifulSoup as bs
import requests
url = "https://www.stackoverflow.com/"

html_content = requests.get(url).text
soup = bs(html_content, "html.parser")

if soup.find('title').text is not None:
  print(soup.find('title').text)

Output:

Stack Overflow - Where Developers Learn, Share, & Build Careers

Here, you will notice that the if condition we used is is not None to ensure we’re calling an existing method. Now, it will not show any error such as the AttributeError.

При парсинге периодически выдается ошибка «AttributeError: ‘NoneType’ object has no attribute ‘text'», т.к. парсер не может найти нужный элемент по селектору и узнать у него text.

Данные получаю так:
fax = soup.find(id="ctl0_left_fax")

Затем добавляю в массив (на этом скрипт спотыкается): 'fax': fax.text.strip(),

Пробовал сделать проверку:

#  Проверяю, если у страницы TITLE пустой, значит там нечего парсить. ХОЧУ ПРОПУСТИТЬ ДАЛЬНЕЙШИЙ  ПАРСИНГ
if (len(soup.title.text.strip()) == 15) or (soup.title.text.strip() == 'testtesttest -'):
    exit
#  Если у страницы TITLE <16 (значит там есть какой-то контент), то посмотреть текст у селекторов
else:
    list = {
               'cap': cap.text.strip(),
               'fax': fax.text.strip(),
               'email': email.text.strip(),
        }

Но почему-то это игнорируется (хотя проверял — работает).

Добавлю, что реализовал подобный алгоритм на PHP и у меня все работало.

Более того, на этапе добавления в массив я ПРЯМО В НЕМ проверял через возвращаемый тип данных через тернарный оператор, но в питоне это не проходит.

In this article, we will take a closer look at this error Attributeerror nonetype object has no attribute text solutions and what it means.

Let’s get started!

The AttributeError ‘NoneType’ object has no attribute ‘text’ error means that you are trying to access the text attribute of a NoneType object.

In Python, the NoneType object is used to represent the absence of a value. The text attribute, on the other hand, is a common attribute used in Python for strings, lists, and other objects.

Moreover, it allows you to access the text content of an object, which can be useful in various applications.

This nonetype object has no attribute text typically happens when a function or method returns None, and you try to access an attribute of the return value.

How this error occur?

Here’s an example of an “AttributeError: ‘NoneType’ object has no attribute ‘text’” error:

my_string = None
print(my_string.text)

Result:

AttributeError: 'NoneType' object has no attribute 'text'

In this case, when you try to access the “text” attribute of “my_string“, Python will raise an “AttributeError” because “my_string” is a “NoneType” object, which doesn’t have a “text” attribute.

How to solve Attributeerror nonetype object has no attribute text

The ‘NoneType’ object has no attribute ‘text’ error usually occurs when trying to access the .text attribute of a variable that is None.

There are several ways to solve this error, and here are three of them with example codes:

1. Check if the variable is None before accessing its .text attribute:

Make sure that the variable you are trying to access is defined and has a value assigned to it. If the variable is not defined, you will need to define it before accessing its ‘text’ attribute.

# Example code
some_variable = None

if some_variable is not None:
    print(some_variable.text)
else:
    print("The variable is None.")

Output:

The variable is None.

2. Use a default value if the variable is None:

# Example code
some_variable = None

text_value = some_variable.text if some_variable is not None else "Default value"
print(text_value)

Output:

Default value

3. Handle the error with a try/except block:

You can handle the error ‘NoneType’ object has no attribute ‘text’ with a try-except block. In this way, if the ‘text‘ attribute does not exist, the error will be caught and you can handle it gracefully.

# Example code
some_variable = None

try:
    print(some_variable.text)
except AttributeError:
    print("The variable is None and has no .text attribute.")

Output:

The variable is None and has no .text attribute.

Anyhow, if you are finding solutions to some errors you might encounter we also have Typeerror: unhashable type: ‘slice’.

Conclusion

The AttributeError 'NoneType' object has no attribute 'text' error message can be frustrating, but it’s a common error that you may encounter when working with Python.

By understanding the causes of the error and using the techniques outlined in this article, you can avoid or handle the error and keep your code running smoothly.

We hope that this article has helped you resolve this error and that you can now continue working on your Python projects without any issues.

Hi @kennethreitz ,

I am sorry to bother you with this. I don’t know why I am getting this error with your example on http://html.python-requests.org/

Here is the code:

from requests_html import HTMLSession
session = HTMLSession()
r = session.get(‘https://github.com/’)
sel = ‘body > div.application-main > div.jumbotron.jumbotron-codelines > div > div > div.col-md-7.text-center.text-md-left > p’

print(r.html.find(sel, first=True).text)

This is the error I am getting. Any idea? I tested it on both Windows 10 and Ubuntu 16.04 and I am getting the same error. I am also using Python 3.6 (Anaconda).

AttributeError Traceback (most recent call last)
in ()
4 sel = ‘body > div.application-main > div.jumbotron.jumbotron-codelines > div > div > div.col-md-7.text-center.text-md-left > p’
5
—-> 6 print(r.html.find(sel, first=True).text)

AttributeError: ‘NoneType’ object has no attribute ‘text’

Понравилась статья? Поделить с друзьями:
  • Ntp клиент поставщика времени ошибка
  • Non zero exit code 2 pycharm ошибка
  • Ntfs file system ошибка windows 10 как исправить
  • Non system disk or disk error как исправить ошибку
  • Non orthogonal matrix support 3d max ошибка