проблема с парсером AttributeError: 'NoneType' object has no attribute 'get'
import requests
from bs4 import BeautifulSoup
zona = input("Введите значение отдела(Запрещённые судом курсы и книги - 971): ")
fov = int(input("Введите число страниц(+1; Например: страниц 40, мы пишем 41): "))
headers = {
'Host': 'vavilon.cc',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36 OPR/87.0.4390.25',
'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate, br',
'Connection': 'keep-alive'
}
tot = []
for count in range(1, fov):
url = f'https://vavilon.cc/forums/{zona}/page-{count}'
va_request = requests.get(url, headers=headers, auth=('ing2123', 'Mixail21212'))
# print(va_request.status_code)
va_soup = BeautifulSoup(va_request.text, "lxml")
av = va_soup.find_all("div", {'class': 'structItem-title'})
# print(av)
for i in av:
title = i.find("a", {'data-xf-init': 'preview-tooltip'})
titn = "https://vavilon.cc" + title.get("href")
tit = title.get_text()
tot.append(
{
'Название': tit,
'Ссылка': titn
}
)
with open('va.txt', 'w') as file:
print(*tot, file=file, sep="\n")
# print(tot)
Выводит:
Traceback (most recent call last):
File "C:\py\ag\va.py", line 38, in <module>
print(*tot, file=file, sep="\n")
File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\encodings\cp1251.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\xd7' in position 42: character maps to <undefined>
И иногда:
Traceback (most recent call last):
File "C:\py\ag\va.py", line 29, in <module>
titn = "https://vavilon.cc" + title.get("href")
AttributeError: 'NoneType' object has no attribute 'get'
Подскажите как решить проблему с Traceback (most recent call last) и как сделать запись в файл не в строку, а в виде:
tot.append(
{
'Название': tit,
'Ссылка': titn
}
)
Ответы (1 шт):
Автор решения: miha_tormoz
→ Ссылка
Спасибо CrazyElf и KoVadim, теперь всё работает как надо.
va_soup = BeautifulSoup(va_request.content, "lxml")
av = va_soup.find_all("div", {'class': 'structItem-title'})
# print(av)
for i in av:
title = i.find("a", {'data-xf-init': 'preview-tooltip'})
if title is None: continue
titn = "https://vavilon.cc" + title.get("href")
tit = title.get_text()
tot.append(
{
'Название': tit,
'Ссылка': titn
}
)
with open('va.txt', 'w', encoding="utf-8") as file:
print(*tot, file=file, sep="\n")