Я пытаюсь отобразить названия новостей с сайта http://hkotso.ru/novosti, но в коде отображается ошибка
import requests
from bs4 import BeautifulSoup as bs
r = requests.get('http://hkotso.ru/novosti')
html = bs(r.content,'html.parser')
for el in html.select('.views-row-odd'):
title = el.select('.media-heading > a')
print(title.text)
for el in html.select('.views-row-even'):
title = el.select('.media-heading > a')
print(title.text)
Этот код выдает ошибку:
Traceback (most recent call last):
File "par.py", line 9, in <module>
print(title.string)
File "C:\Users\max\AppData\Local\Programs\Python\Python38-32\lib\site-packages\bs4\element.py", line 2080, in __getattr__
raise AttributeError(
AttributeError: ResultSet object has no attribute 'string'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?
Я пытаюсь отобразить названия новостей с сайта http://hkotso.ru/novosti, но в коде отображается ошибка
Ответы (1 шт):
Автор решения: Wairua
→ Ссылка
from bs4 import BeautifulSoup as Soup
import requests
def page_proc(page: Soup) -> list:
news_headers = []
for header in page.find_all('h4', {'class': 'media-heading'}):
news_headers.append(header.text.strip())
return news_headers
def sandbox(base_url: str) -> list:
headers = []
with requests.Session() as session:
first_page = Soup(session.get(base_url).content, 'html.parser')
pages_qty = int(first_page.find('li', {'class': 'pager-last'}).a['href'].rpartition('=')[-1])
headers.extend(page_proc(first_page))
for p in range(2, pages_qty + 1):
pg = Soup(session.get(base_url + f'?page={p}').content, 'html.parser')
headers.extend(page_proc(pg))
return headers
if __name__ == '__main__':
print(sandbox('http://hkotso.ru/novosti'))