python Selenium как провалиться по дереву элементов

есть вопрос по селениуму, вот у меня есть сайт в котором нужно вытянуть данные о цене моментальной продажи автомобиля

введите сюда описание изображения

Но он имеет абсолютно те же самые селекторы и классы что и размер ставки аукциона

введите сюда описание изображения

Я попытался вытянуть хотя бы и то и то, но вытягивает только второй вариант, а первый вообще не цепляет, как можно было бы решить эту проблему?

Вот мой код:

 for item_el in driver.find_elements_by_css_selector(".plc-db__lot-item"):
                item_name = item_el.find_element_by_css_selector(".plc-db__lot-item__title")
                name = item_name.get_attribute("title")
                price = item_el.find_element_by_tag_name("bdi").text
                print(name, "||", price)


И вот что выводит:

2010 Toyota Hilux  || 380 $
2010 Toyota Land Cruiser  || 761 $
2012 Toyota Coaster  || 163 $
2016 Nissan Patrol  || 489 $
2010 Chevrolet Express  || 408 $
2014 Nissan Patrol  || 326 $
2017 BMW X5  || 897 $
2018 Polaris  || 2121 $
2011 BMW 535 i  || 108 $
2017 Toyota 86  || 6800 $
2009 Hyundai County  || 4080 $
2012 Hyundai Grand  || 897 $
2019 XCMG GTBZ22S  || 272 $
2018 Caterpillar 216B3  || 13708 $
2018 XCMG GTBZ22S  || 272 $
2014 Lexus IS 350  || 10064 $

Вот пример элемента который я хочу вывести:

<div class="plc-db__lot-item  plc-db__lot-item-instock p-2 background-white" id="plc-db-id-123873">
    <div class="row no-gutters">

        <div class="col-12 d-md-none">
            <div class="plc-db__lot-item__header row no-gutters mb-2">

    <div class="col">
                <a href="https://plc.ua/ua/autos/uae/lot/nissan-patrol-2019-dc-520045/" class="text-decoration-none  plc-db__lot-item__title text-uppercase font-weight-bold mb-2" title="2019 Nissan Patrol Platinum City">
            <span class="text-gray">2019</span> <span class="text-primary">Nissan</span> Patrol Platinum City        </a>
    </div>


    
    </div>
        </div>

        <div class="col-12 col-md-auto pr-md-3">
            <a href="https://plc.ua/ua/autos/uae/lot/nissan-patrol-2019-dc-520045/" title="2019 Nissan Patrol Platinum City" class="plc-db__lot-item__preview plc-radius overflow-hidden">
                <img src="https://img.plc.ua/medium/img3/10/2019/10/6909/62221ad426d39821a8f39ac81bb02e07/cab8743bcd01db63ad372cb408a54c90.jpg" onerror="this.src='https://plc.ua/wp-content/themes/plc/public/img/placeholder.svg'" alt="2019 Nissan Patrol Platinum City" title="2019 Nissan Patrol Platinum City" loading="lazy">            </a>
        </div>

        <div class="col-12 col-md">
            <div class="plc-db__lot-item__content_wrap">
                <div class="d-none d-md-block">
                    <div class="plc-db__lot-item__header row no-gutters mb-2">

    <div class="col">
                <a href="https://plc.ua/ua/autos/uae/lot/nissan-patrol-2019-dc-520045/" class="text-decoration-none  plc-db__lot-item__title text-uppercase font-weight-bold mb-2" title="2019 Nissan Patrol Platinum City">
            <span class="text-gray">2019</span> <span class="text-primary">Nissan</span> Patrol Platinum City        </a>
    </div>


    
    </div>
                </div>
                <div class="plc-db__lot-item__content mt-3 mt-md-0">
    <div class="row text-gray font-size-sm justify-content-center justify-content-md-start">
                            <div class="justify-content-center col-auto text-nowrap d-flex align-items-center mb-3 lot-item__attributes">
                <svg class="mr-2 icon-calendar icon-svg"><use xlink:href="https://plc.ua/wp-content/themes/plc/public/svg/sprite.lot.svg?1615450354#calendar"></use></svg> 2019            </div>
                            <div class="justify-content-center col-auto text-nowrap d-flex align-items-center mb-3 lot-item__attributes">
                <svg class="mr-2 icon-gas-station icon-svg"><use xlink:href="https://plc.ua/wp-content/themes/plc/public/svg/sprite.lot.svg?1615450354#gas-station"></use></svg> Бензин            </div>
                            <div class="justify-content-center col-auto text-nowrap d-flex align-items-center mb-3 lot-item__attributes">
                <svg class="mr-2 icon-road icon-svg"><use xlink:href="https://plc.ua/wp-content/themes/plc/public/svg/sprite.lot.svg?1615450354#road"></use></svg> 57 000 км            </div>
                                            <div class="justify-content-center col-auto text-nowrap d-flex align-items-center mb-3 lot-item__attributes">
                <svg class="mr-2 icon-car icon-svg"><use xlink:href="https://plc.ua/wp-content/themes/plc/public/svg/sprite.lot.svg?1615450354#car"></use></svg> Кросовер            </div>
                            <div class="justify-content-center col-auto text-nowrap d-flex align-items-center mb-3 lot-item__attributes">
                <svg class="mr-2 icon-gears icon-svg"><use xlink:href="https://plc.ua/wp-content/themes/plc/public/svg/sprite.lot.svg?1615450354#gears"></use></svg> Автомат            </div>
                                    <div class="justify-content-center col-auto text-nowrap d-flex align-items-center mb-3 lot-item__attributes">
                <svg class="mr-2 icon-damage icon-svg"><use xlink:href="https://plc.ua/wp-content/themes/plc/public/svg/sprite.lot.svg?1615450354#damage"></use></svg> Відсутні            </div>
            </div>
</div>                <div class="plc-db__lot-item__footer">
                    <div class="row">
                        <div class="col-6 col-lg-auto d-flex align-items-center order-0 order-md-2 mb-2 mb-md-0 justify-content-center">
                            <span class="lot__item-price lot__item-price_buy">
                                <svg class="mr-2 icon-svg"><use xlink:href="https://plc.ua/wp-content/themes/plc/public/svg/sprite.lot.svg?1615450354#auction"></use></svg> <span class="woocommerce-Price-amount amount"><bdi>0&nbsp;<span class="woocommerce-Price-currencySymbol">$</span></bdi></span>                            </span>
                        </div>

                                                    <div class="col-6 col-lg-auto d-flex align-items-center order-0 order-md-2 mb-2 mb-md-0 justify-content-center">
                                <span class="lot__item-price lot__item-price_buy">
                                    <svg class="mr-2 icon-svg"><use xlink:href="https://plc.ua/wp-content/themes/plc/public/svg/sprite.lot.svg?1615450354#buy"></use></svg> <span class="woocommerce-Price-amount amount"><bdi>60810&nbsp;<span class="woocommerce-Price-currencySymbol">$</span></bdi></span>                                </span>
                            </div>
                                            </div>
                    <div class="row mt-2 justify-content-between">
                                                                            <div class="col-6 col-md-5 pr-1">
                                <span class="btn btn-primary text-uppercase plc-db__lot-item__button " data-remodal-target="order-auto" data-remodal-referer="https://plc.ua/ua/autos/uae/lot/nissan-patrol-2019-dc-520045/">
    замовити</span>
                            </div>
                                                <div class="col-6 col-md-5 pl-1">
                            <a href="https://plc.ua/ua/autos/uae/lot/nissan-patrol-2019-dc-520045/" title="2019 Nissan Patrol Platinum City" class="btn btn-secondary text-uppercase plc-db__lot-item__button">
    докладніше</a>                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

И вот ссылка на страницу где он находится: https://plc.ua/ua/autos/uae/page/8/?limit=30

Полный код можно взять вот тут: https://dpaste.org/0Bxa1

Помогите пожалуйста!


Ответы (1 шт):

Автор решения: Константин Николаевич Бояр II

Видимо в таком случае один из вариантов получения элемента который является ценой для моментальной продажи - это итерация по xpath, попробуйте вот такой вариант:

options = Options()
    options.add_argument('--headless')

    items_name = []
    items_price = []
    urls = []

    driver = webdriver.Firefox(options=options)

    try:
        page = last_page = 8
        while page <= last_page:
            url = url
            if page > 1:
                url = f'https://plc.ua/ua/autos/uae/page/{page}/?limit=30'

            print(f'Load: {url}')
            driver.get(url)

            for item_el in driver.find_elements_by_css_selector(".plc-db__lot-item"):
                item_name = item_el.find_element_by_css_selector(".plc-db__lot-item__title")
                names = item_name.get_attribute("title")
                name = names
                items_name.append(name)
            for i in range(1,30):
                try:
                    price = item_el.find_element_by_xpath(f"/html/body/main/div[1]/div[3]/div/div[3]/div/div/div[2]/div[{i}]/div/div[3]/div/div[3]/div[1]/div[2]").text
                except:
                    price = '-'

                items_price.append(price)
                #print(price)
            # Обновление номера последней страницы
            try:
                last_page = 9

            except NoSuchElementException:
                break

            page += 1

    finally:
        driver.quit()
    
    for actual_name, actual_price in zip(items_name, items_price):
        row = actual_name, actual_price
        print(row)

Вот что у меня получилось вывести:

('2010 Toyota Land Cruiser ', '-')
('2010 Toyota Land Cruiser ', '-')
('2010 Toyota Land Cruiser ', '-')
('2010 Toyota Land Cruiser ', '-')
('2010 Toyota Hilux ', '-')
('2010 Toyota Land Cruiser ', '-')
('2012 Toyota Coaster ', '-')
('2016 Nissan Patrol ', '-')
('2010 Chevrolet Express ', '-')
('2014 Nissan Patrol ', '-')
('2017 BMW X5 ', '-')
('2018 Polaris ', '-')
('2011 BMW 535 i ', '-')
('2017 Toyota 86 ', '-')
('2020 Toyota Hilux VEHICLE NO', '-')
('2021 Mercedes-Benz E 200 E200 C0UPE', '63513 $')
('2019 Nissan Patrol Platinum City', '60810 $')
('2013 BMW 640 640i M Sport Grand Coupe', '20270 $')
('2016 Nissan Versa Nissan Versa US specs Ref# 356', '6081 $')
('2016 Nissan X-Trail Nissan X-Trail 2006 Japanese specs Ref# 355', '4729 $')
('2010 Nissan Versa Nissan Versa US specs Ref# 357', '4729 $')
('2020 CMC Veryca CMC Veryca Freezer Ref# 350', '10000 $')
('2017 Mitsubishi Lancer Mitsubishi Lancer Full options Ref# 359', '10135 $')
('2022 Toyota Land Cruiser GR SPORT TWIN TURBO 3', '-')
('2013 Mitsubishi Pajero GLS ميتسوبيشي باجيرو خليجي بدون حوادث نهائيآ لا تحتاج لأي مصروف', '8648 $')
('2022 BMW X3 xDrive30i 2', '-')
('2020 Mercedes-Benz E 300 Premium', '200000 $')
('2021 Mercedes-Benz G 500 Std MERCEDES G 500 IN IMMACULATE CONDITION ONLY 4100 KM FOR 649K AED', '175405 $')
('2016 Nissan Patrol () V8 LE T2, GCC', '41891 $')
('2012 Mercedes-Benz CLS 63 AMG Mercedes CLS 63 AMG__Excellend_condihich', '10700 $')
('2013 Ford Expedition Ford Expedition__Excellend_condihich', '11500 $')
('2014 Kia Mohave Kia Mohave Top__Excellend_condihich', '10810 $')
('2017 Mitsubishi Lancer', '17837 $')
('2019 Hyundai Kona', '15405 $')
('2010 Nissan Patrol Safari', '13243 $')

Проверяем случайную цену, например 2010 Nissan Patrol Safari на сайте и видим что код отрабатывает на ура

введите сюда описание изображения

('2021 Mercedes-Benz E 200 E200 C0UPE', '63513 $')

Надеюсь помог :)

→ Ссылка