0

В переменной link функции get_page_data(html) находятся ссылки со страниц которых хочу получить все заголовки h1. Сейчас парсер получает заголовок последней страницы списка link. Как получить список заголовков h1 со всех страниц из списка link?

import requests
from bs4 import BeautifulSoup

def get_html(url):
    r = requests.get(url)
    return r.text

def get_page_data(html):
    soup = BeautifulSoup(html, 'lxml')

    ads = soup.find("nav", class_="main-mnu hidden-md hidden-sm hidden-xs").find("ul").find_all("li")
    for ad in ads:
        urls = ad.find("a").get("href")
        link = "https://gbcrem.by" + urls
        # Печатаем список ссылок
        print(link)

    return link

def get_content(html, links):
    r = requests.get(links)
    # Печатаем ссылки которые возвращает links
    print(r.url)

    return r.text

def get_h_content(html):
    soup = BeautifulSoup(html,'lxml')
    page_url = soup.find_all("body", class_="ishome")
    for ad in page_url:
        h = ad.find_all("h1")
        # Печатаем все заголовки h1 для каждой ссылки из списка
        print(h)

def main():

    url = "https://gbcrem.by"

    html = get_html(url)
    get_page_data(html)

    links = get_page_data(html)
    get_content(html, links)

    html = get_content(html, links)
    get_h_content(html)

if __name__ == '__main__':
    main()

1 ответ 1

1

Из get_page_data нужно возвращать список ссылок, а не только последнюю ссылку:

def get_page_data(html):
    soup = BeautifulSoup(html, 'lxml')

    links = []

    ads = soup.find("nav", class_="main-mnu hidden-md hidden-sm hidden-xs").find("ul").find_all("li")
    for ad in ads:
        urls = ad.find("a").get("href")
        link = "https://gbcrem.by" + urls
        # Печатаем список ссылок
        print(link)
        links.append(link)

    return links

После пройтись по ссылкам, скачать, распарсить и вытащить из них h1:

links = get_page_data(html)
for url in links:
    html = get_html(url)
    get_h_content(html)

PS.

Если нужно чтобы функция get_h_content возвращала список заголовков, то делайте по аналогии с get_page_data – заводите список, заполняйте и возвращайте его

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.