Python - поиск содержимого кнопки «развернуть» с помощью beautifulsoup.

Я просматриваю желтую страницу, чтобы узнать имена всех физиотерапевтов в городе. С URL-адресом я получаю список из 50 физиотерапевтов, однако, когда я расширяю страницу, URL-адрес не меняется. Как мне получить полный список имен?

Так я попал в список физиотерапевтов в Ростоке.

      url = 'https://www.gelbeseiten.de/Suche/Physiotherapie%20praxis/Rostock'
req = requests.get(url, headers= header)
soup = BeautifulSoup(req.content, 'html.parser')

names = []

business_name = soup.find_all('h2', attrs ={"data-wipe-name":"Titel"})
for name in business_name:
    
    names.append(name.get_text())

Внизу URL-адреса есть кнопка под названием , в основном говоря "покажи еще". Если я щелкну здесь, количество записей для физиотерапевтов изменится с 50-60. Есть записи для 90 физиотерапевтов. Когда я нажимаю кнопку несколько раз, показывая все записи, кнопка исчезает. Здесь перечислены все физиотерапевты города, я хочу это получить.

Как мне получить все записи, которые я получаю после нажатия кнопки «показать больше»?

2 ответа

Для этой простой задачи нет необходимости использовать Selenium. Используя инструменты разработчика Chrome, вы можете заметить, что веб-сайт использует простой запрос POST для https://www.gelbeseiten.de/AjaxSuche при нажатии кнопки Mehr anzeigen, содержащей следующие данные:

      umkreis: -1
WAS: Physiotherapie praxis
WO: rostock
position: 51
anzahl: 10
sortierung: relevanz

Ответ json содержит htmlключ, содержащий все ваши результаты поиска. Дополнительно есть gesamtanzahlTreffer а также anzahlTrefferключи внутри ответа. К сожалению, невозможно получить все результаты поиска с помощью одного запроса POST, установив position=0 а также anzahl=100. Однако первый запрос POST содержит первые 50 результатов (аналогично веб-сайту), и с каждым новым запросом POST мы можем получить следующие 10 результатов.

Короче говоря, вы можете проанализировать все результаты следующим образом:

      def post_ajax_search(was: str, wo: str, pos: int):
    req = requests.post("https://www.gelbeseiten.de/AjaxSuche", data={
        'umkreis': -1, 'WAS': was, 'WO': wo, 'position': pos, 'sortierung': 'relevanz'})
    r = req.json()
    return [r[key] for key in ("gesamtanzahlTreffer", "html", "anzahlTreffer")]


def parse_html(html: str) -> list[str]:
    soup = BeautifulSoup(html, "lxml")
    return [i.text for i in soup.find_all("h2", {"data-wipe-name": "Titel"})]


def parser(was: str, wo: str) -> list[str]:
    total_treffer, html, parsed_treffer = post_ajax_suche(was, wo, 0)
    all_items = parse_html(html)
    i = 0
    while parsed_treffer < total_treffer:
        _, html, treffer = post_ajax_suche(was, wo, 51 + i)
        all_items += parse_html(html)
        parsed_treffer += treffer
        i += 10
    return all_items

for praxis in (praxen := parser("Physiotherapie praxis", "rostock")):
    print(praxis)

Выход:

      Göllner Sabine Krankengymnastik & Physiotherapie
Friemel Physiotherapie Inh. B. Neumann Krankengymnastik & Physiotherapie
Nehrenberg Dorothee Physiotherapie
Physiotherapiezentrum Marcel Frank
Silke Thiede Physiotherapie
Physiotherapie Kollmorgen
Buller Olaf Physiotherapie
Gemeinschaftspraxis Physiotherapie Möller & Norden
Physiotherapie Annekathrin Hinz
Physiotherapie Hinz Annekathrin Praxis für Physiotherapie
Physiotherapie K. Schuldt
Physiotherapie Richter Ralf-Uwe Physiotherapie
Sport-Physio Rostock, Inh. Tschiersch, Daniel Physiotherapie
Klimt Dagmar Physiotherapie
MedPrevio
Pause Andrea Physiotherapiepraxis
Sörgel Steffen
Doremans Monika Physiotherapie
Doremans Monika Physiotherapie
Friemel B. Physiotherapie
Physiotherapie Vital Speicher Katja Oestreich
Jürß Katherina Physiotherapie
Pietralczyk Regina Physiotherapie
Stoll Sven Physiotherapie
Tübbecke Carola Physiotherapie
Physiotherapie Reiser u. Behrens
Physiotherapeutische Praxis Rose
Arndt K. Physiotherapie
Arndt K. Physiotherapie
Hieke Gunnar Praxis für Physiotherapie
PTB Physiopraxis
PTB Physiopraxis
Physiotherapie Rhea Brüdigam
Duske Sandra
Achsnig Marion Physiotherapie
Berthold Physiopraxis
Bohn Katharina Praxis für Physiotherapie
Erdmann L. Physiotherapie
Hennig Heidlinde Physiotherapie
Klatt Gabriele Physiotherapie
Physio- & Hydrotherapie Evelyn Ruß-Deuschle
Physiometik-Physiotherapie und Kosmetik
PhysioPlus Martin Berthold
Physiotherapie Elke Wegener
Physiotherapie Inh. Doreen Bastian
Therapiewelten Fromm Inh. Andrea Fromm Physiotherapie
Therapiewelten Fromm Inh. Andrea Fromm Physiotherapie
Therapiewelten Fromm Inh. Andrea Fromm Physiotherapie
vital & physio GmbH Portwich, Rene & Kristina
Neumann Andre Physiotherapie
Physiotherapie Heike Braun u.Gisela Wessel-Schutz
Physiotherapie Monika Laasch
Physiotherapiepraxis Briese Inke u. Engel Katrin
Schawaller, Mertens Physiotherapie
Ahrens Ch. Hoffmann B. Kautz K. Wiechert M. Physiotherapiepraxis
Lenz Andrea Praxis für Physiotherapie
PhysioKiDa
Physiotherapie Birgit Paul
Physiotherapie Hirsch U.
Maaß Ingrid Physiotherapie
Physiotherapie Birgit Vogt
Müller Holger Physiotherapie
Physiotherapie A. Fischer-Pifrement
Physiotherapie Schuberth Simone
Skupin Anne, Praxis für Physiotherapie und Kinderphysiotherapie
Stoll Sven Physiotherapie
Physiotherapiepraxis Lasch
Physiotherapie Leyer
Simon Petra Physiotherapie
Erdmann Petra Physiotherapeutische Praxis
Doremans-Harms Monika Physiotherapie
Holz-Gräfe Ulrike Physiotherapie
Kannenberg u. Swensson Praxisgemeinschaft für Physiotherapie
Keßler Dirk Physiotherapie
Physiotherapie Ahrens Ch., Hoffmann B., Kautz K. u. Wiechert M.
Physiotherapie Dorit Schumacher Praxis für Physiotherapie
Physiotherapie Höhnerbach
Physiotherapie Kerstin Wikert Physiotherapeutin
Physiotherapie Kollmorgen
Physiotherapie Neumann
Physiotherapie Physikalische Therapie Inh. Karin Hellmuth
Physiotherapiepraxis Angela Keller
Pöschmann Kathleen Menschen"s"kinder Physiotherapie
PTB Physiopraxis
Roberto Kollmorgen
Rothkirch Physiotherapie Ramona
Schmidt Josephine Praxis für Physiotherapie
Stoll Sven Physiotherapie
Strauß Arne
Thoms Christiane Physiotherapie

BeautifulSoup - это анализатор HTML.

Если вам нужно нажимать кнопки на HTML-странице, используйте инструмент, который использует настоящий браузер, например селен.

В случае, если вы не хотите узнавать о Selenium, хакерское решение - загрузить HTML после нажатия кнопки Mehr Anzeigenа затем проанализируйте это с помощью BeautifulSoup. Вот вставка HTML-кода после отображения всех 90 записей: https://pastebin.pl/view/raw/277d9ea1

Другие вопросы по тегам