Нету класса у блока span
из за того что на некоторых отелях нету оценки, выдает ошибку что у блока нету атрибута текст. Как можно обойти это
код:
import requests
import lxml
from bs4 import BeautifulSoup
import csv
def get_data(url):
headers = {
'User Agent': 'Mozilla / 5.0(WindowsNT10.0; Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 110.0.0.0 Safari / 537.36'
}
req = requests.get(url=url)
#with open('index.html', 'w', encoding='utf8') as file:
#file.write(req.text)
soup = BeautifulSoup(req.text, 'lxml')
hotel_cards = soup.find_all('li', class_='item')
#print(hotel_cards)
for hotel_url in hotel_cards:
hotel_url = 'https://101hotels.com' + hotel_url.find('a').get('href')
#print(hotel_url)
for title_hotels in hotel_cards:
title_hotels = title_hotels.find('a').text
#print(title_hotels)
for hotel_price_result in hotel_cards:
hotel_price = hotel_price_result.find('span', class_='price-highlight').text.strip()
hotel_price2 = hotel_price_result.find('span', class_='currency').text.strip()
price_with_currency = f'{hotel_price} {hotel_price2}'
#print(price_with_currency)
for hotel_rating in hotel_cards:
hotel_rating = hotel_rating.find('span', {"itemprop": "ratingValue"}).text.strip()
print(hotel_rating)
def main():
get_data('https://101hotels.com/main/cities/yuzhno-sakhalinsk')
if __name__ == '__main__':
main()
Источник: Stack Overflow на русском