Соскоб html идентификатор с Beautifulsoup - PullRequest
2 голосов
/ 08 апреля 2020

У меня проблемы с удалением идентификаторов html из приведенного ниже файла html, потому что есть две строки кода, у которых нет идентификатора под 14 Jun 2020, что означает, что после назначения слотов больше нет 8.15am on 14 June, встречи возобновляются 15 июня.

<table class="table table-borderless table-striped no-background clear-padding-first-child available-slots-mobile main-table clone">
    <thead>
        <tr>
            <th width="14%" class="text-left nowrap fixed-side">Session Date</th>
            <th width="14%" class="text-center">
                <b>1</b>
            </th>
            <th width="14%" class="text-center">
                <b>2</b>
        </tr>
    </thead>
    <tbody class="tr-border-bottom">
        <tr>
            <th class="pb-15 text-left fixed-side">
                <a href="javascript:changeDate('13 Jun 2020');">13 Jun 2020</a>
                <br> Saturday
            </th>
            <td class="pb-15 text-center">
                <a href="#" id="1217464_1_13/6/2020 12:00:00 AM" class="slotBooking">
                                                                        8:15 AM ✔
                                                                    </a>
            </td>

        </tr>
        <tr>
            <th class="pb-15 text-left fixed-side">
                <a href="javascript:changeDate('14 Jun 2020');">13 Jun 2020</a>
                <br> Sunday
            </th>
            <td class="pb-15 text-center">
                <a href="#" id="1217482_1_14/6/2020 12:00:00 AM" class="slotBooking">
                                                                        8:15 AM ✔
                                                                    </a>
            </td>
            <td class="pb-15 text-center"><span class="c-gray">n/a</span></td>
            <td class="pb-15 text-center"><span class="c-gray">n/a</span></td>
        </tr>
        <tr>
            <th class="pb-15 text-left fixed-side">
                <a href="javascript:changeDate('15 Jun 2020');">15 Jun 2020</a>
                <br> Monday
            </th>

            <td class="pb-15 text-center">
                <a href="#" id="1217506_1_15/6/2020 12:00:00 AM" class="slotBooking">
                                                                        8:15 AM ✔
                                                                    </a>
            </td>
        </tr>
    </tbody>
</table>

Я пришел с приведенным ниже кодом, но будут напечатаны только html идентификаторы встреч до 8.15am 14th June 2020 slot. Затем я сталкиваюсь с TypeError (объект NoneType не повторяется) после того, как был напечатан идентификатор слота 8.15am 14 June, и не напечатаны идентификаторы слотов 15 июня.

for slots in soup.findAll(attrs={"class" : "pb-15 text-center"}):
    tags = slots.find("a")
    for IDS in tags:
        IDS = tags.attrs["id"]
    print (IDS)

Я также попытался обработать исключение здесь, но я столкнулся с синтаксической ошибкой (и я не слишком уверен, что именно я сделал неправильно).

for slots in soup.findAll(attrs={"class" : "pb-15 text-center"}):
    tags = slots.find("a")
    for IDS in tags:
        try:
            IDS = tags.attrs["id"]
        except TypeError:
            else:
            print (IDS)

Ответы [ 2 ]

2 голосов
/ 08 апреля 2020

Просто проверьте, есть ли тег с атрибутом id, затем напечатайте его.

data='''<table class="table table-borderless table-striped no-background clear-padding-first-child available-slots-mobile main-table clone">
    <thead>
        <tr>
            <th width="14%" class="text-left nowrap fixed-side">Session Date</th>
            <th width="14%" class="text-center">
                <b>1</b>
            </th>
            <th width="14%" class="text-center">
                <b>2</b>
        </tr>
    </thead>
    <tbody class="tr-border-bottom">
        <tr>
            <th class="pb-15 text-left fixed-side">
                <a href="javascript:changeDate('13 Jun 2020');">13 Jun 2020</a>
                <br> Saturday
            </th>
            <td class="pb-15 text-center">
                <a href="#" id="1217464_1_13/6/2020 12:00:00 AM" class="slotBooking">
                                                                        8:15 AM ✔
                                                                    </a>
            </td>

        </tr>
        <tr>
            <th class="pb-15 text-left fixed-side">
                <a href="javascript:changeDate('14 Jun 2020');">13 Jun 2020</a>
                <br> Sunday
            </th>
            <td class="pb-15 text-center">
                <a href="#" id="1217482_1_14/6/2020 12:00:00 AM" class="slotBooking">


                                             8:15 AM ✔
                                                                    </a>
            </td>
            <td class="pb-15 text-center"><span class="c-gray">n/a</span></td>
            <td class="pb-15 text-center"><span class="c-gray">n/a</span></td>
        </tr>
        <tr>
            <th class="pb-15 text-left fixed-side">
                <a href="javascript:changeDate('15 Jun 2020');">15 Jun 2020</a>
                <br> Monday
            </th>

            <td class="pb-15 text-center">
                <a href="#" id="1217506_1_15/6/2020 12:00:00 AM" class="slotBooking">
                                                                        8:15 AM ✔
                                                                    </a>
            </td>
        </tr>
    </tbody>
</table>'''

soup=BeautifulSoup(data,'html.parser')

for slots in soup.findAll(attrs={"class" : "pb-15 text-center"}):
    tag= slots.find("a",id=True)
    if tag:
        print(tag.attrs["id"])

Вы можете добиться того же, используя один селектор css.

for slots in soup.select('.pb-15.text-center>a[id]'):
    if slots:
        print(slots.attrs["id"])

Выход :

1217464_1_13/6/2020 12:00:00 AM
1217482_1_14/6/2020 12:00:00 AM
1217506_1_15/6/2020 12:00:00 AM

Обновление

for slots in soup.findAll(attrs={"class" : "pb-15 text-center"}):
    tag= slots.find("a",attrs={"id",True})
    if tag:
        print(tag.attrs["id"])
0 голосов
/ 08 апреля 2020
html = '''
<table class="table table-borderless table-striped no-background clear-padding-first-child available-slots-mobile main-table clone">
    <thead>
        <tr>
            <th width="14%" class="text-left nowrap fixed-side">Session Date</th>
            <th width="14%" class="text-center">
                <b>1</b>
            </th>
            <th width="14%" class="text-center">
                <b>2</b>
        </tr>
    </thead>
    <tbody class="tr-border-bottom">
        <tr>
            <th class="pb-15 text-left fixed-side">
                <a href="javascript:changeDate('13 Jun 2020');">13 Jun 2020</a>
                <br> Saturday
            </th>
            <td class="pb-15 text-center">
                <a href="#" id="1217464_1_13/6/2020 12:00:00 AM" class="slotBooking">
                                                                        8:15 AM ✔
                                                                    </a>
            </td>

        </tr>
        <tr>
            <th class="pb-15 text-left fixed-side">
                <a href="javascript:changeDate('14 Jun 2020');">13 Jun 2020</a>
                <br> Sunday
            </th>
            <td class="pb-15 text-center">
                <a href="#" id="1217482_1_14/6/2020 12:00:00 AM" class="slotBooking">
                                                                        8:15 AM ✔
                                                                    </a>
            </td>
            <td class="pb-15 text-center"><span class="c-gray">n/a</span></td>
            <td class="pb-15 text-center"><span class="c-gray">n/a</span></td>
        </tr>
        <tr>
            <th class="pb-15 text-left fixed-side">
                <a href="javascript:changeDate('15 Jun 2020');">15 Jun 2020</a>
                <br> Monday
            </th>

            <td class="pb-15 text-center">
                <a href="#" id="1217506_1_15/6/2020 12:00:00 AM" class="slotBooking">
                                                                        8:15 AM ✔
                                                                    </a>
            </td>
        </tr>
    </tbody>
</table>'''

from bs4 import BeautifulSoup as bs
soup  = bs(html, 'html.parser')
slots = soup.select("td[class='pb-15 text-center'] a")
for slot in slots:
        #slot.attrs is a dictionary so you can avoid NoneType Expection using .get method 
        #slot_id = slot.attrs.get("id",'') this will return '' if there is no id attribute in the tag
        slot_id = slot.attrs.get("id",'')
        print(slot_id)

Выход:

1217464_1_13/6/2020 12:00:00 AM
1217482_1_14/6/2020 12:00:00 AM
1217506_1_15/6/2020 12:00:00 AM
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...