как вывести жанры (types) аниме
как вывести жанры (types) аниме, либо выводит весь текст, либо если ты добавил get_text(), пишет ошибку
Ошибка в 20 строке types": item.find("span", class_ = "anime-genre d-none d-sm-inline") – 'NoneType' object has no attribute 'get_text'
from bs4 import BeautifulSoup, SoupStrainer
import requests
def safe():
with open("parse_info.txt", "a") as file:
file.write(f'{comp["title"]} -> {comp["genres"]} -> {comp["type"]} -> {comp["types"]}\n')
def parse():
URL = "https://animego.org/anime/filter/year-from-2023/apply"
r = requests.get(URL)
html = BeautifulSoup(r.content, "html.parser")
items = html.findAll("div", class_ = "media-body")
comps = []
links = html.findAll('a')
for link in links:
linkdetail = link.get('href')
for item in items:
comps.append({
"title": item.find("div", class_ = "h5 font-weight-normal mb-1").get_text(strip=True),
"genres": item.find("span", class_ = "mb-2").get_text(strip=True),
"type": item.find("a", class_ = "text-link-gray text-underline").get_text(strip=True),
"types": item.find("span", class_ = "anime-genre d-none d-sm-inline")
})
global comp
for comp in comps:
print(f'{comp["title"]} -> {comp["genres"]} -> {comp["type"]} -> {comp["types"]}')
safe()
parse()
Ответы (1 шт):
Автор решения: user510170
→ Ссылка
Как Вам верно заметили в комментариях, не у всех Аниме присутствует описание, поэтому не на каждой странице есть class_ = "anime-genre d-none d-sm-inline" Вы можете обработать эту ошибку в блоке try, except следующим образом.
...
for item in items:
try:
types = item.find("span", class_ = "anime-genre d-none d-sm-inline").get_text(strip=True)
except AttributeError:
types = 'No types'
comps.append({
"title": item.find("div", class_ = "h5 font-weight-normal mb-1").get_text(strip=True),
"genres": item.find("span", class_ = "mb-2").get_text(strip=True),
"type": item.find("a", class_ = "text-link-gray text-underline").get_text(strip=True),
"types": types,
})
...
Теперь если у аниме есть описание, то текст будет сохраняться, а если нет то будет сохраняться No types(можете изменить по Вашему вкусу)