python 'NoneType' object has no attribute 'text'
import datetime
import requests
import lxml
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
url = 'https://magnit.ru/promo/'
def collect_data(city_code='2398'):
cur_time = datetime.datetime.now().strftime('%d_%m_%Y_%H_%M')
ua = UserAgent()
headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
'User-Agent': ua.random
}
cookies = {
'mg_geo_id': f'{city_code}'
}
#responce = requests.get(url, headers=headers, cookies=cookies)
#with open(f'index.html', 'w', encoding="utf8") as file:
#file.write(responce.text)
with open('index.html', encoding="utf8") as file:
src = file.read()
soup = BeautifulSoup(src, 'lxml')
city = soup.find('a', class_='header__contacts-link header__contacts-link_city').text.strip()
cards = soup.find_all('a', class_='card-sale_catalogue')
#print(city, (len(cards)))
for card in cards:
cards_title = card.find('div', class_='card-sale__title').text.strip()
try:
card_discount = card.find('div', class_='card-sale__discount').text.strip()
except AttributeError:
continue
card_price_old_integer = card.find('div', class_='label__price_old').find('span',class_='label__price-integer').text.strip()
card_price_old_decimal = card.find('div', class_='label__price_old').find('span',class_='label__price-decimal').text.strip()
card_old_price = f'{card_price_old_integer}.{card_price_old_decimal}'
card_price_integer = card.find('div', class_='label__price_new').find('span',class_='label__price-integer').text.strip()
card_price_decimal = card.find('div', class_='label__price_new').find('span',class_='label__price-decimal').text.strip()
card_price = f'{card_price_integer}.{card_price_decimal}'
card_sale_date = card.find('div',class_='card-sale__date').text.strip()
print(card_sale_date)
def main():
collect_data(city_code='2398')
if __name__ == '__main__':
main()
никак не могу понять что хочет 39 строка
Консоль:
Traceback (most recent call last):
File "C:\Users\himan\Desktop\pars\main.py", line 62, in <module>
main()
File "C:\Users\himan\Desktop\pars\main.py", line 58, in main
collect_data(city_code='2398')
File "C:\Users\himan\Desktop\pars\main.py", line 39, in collect_data
cards_title = card.find('div', class_='card-sale__title').text
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'text'
Источник: Stack Overflow на русском