Как исключить тег из результата find_all в BeautifulSoup - PullRequest
1 голос
/ 11 апреля 2020

Я пробую Beautiful Soup и использую приведенный ниже код для извлечения некоторого фрагмента данных.

response = requests.get(url_fii, headers=headers)
response.encoding = 'utf-8'
soup = BeautifulSoup(response.text,'html.parser')

print (soup)

Я получаю следующий вывод:

<table class="holiday_list" width="100%">
<tr>
<th colspan="5" style="text-align:center">Heading line</th>
</tr>
<tr>
<th style="text-align:center">Category</th>
<th style="text-align:center">Date</th>
<th style="text-align:center">Value 1</th>
<th style="text-align:center">Value 2</th>
<th style="text-align:center">Value 3</th>
</tr>
<tr class="alt">
<td class="first"> Quantity</td>
<td class="date">09-Apr-2020</td>
<td class="number">7277.03</td>
<td class="number">5539.41</td>
<td class="number">1737.62</td>
</tr>
</table>

Теперь данные, которые меня интересуют, заключены в

:

. С помощью приведенного ниже кода я могу получить все, что хочу:

for p in soup('tr'):
    print (p.text)

Ouput:

Heading line


Category
Date
Value 1
Value 2
Value 3


 Quantity
09-Apr-2020
7277.03
5539.41
1737.62

Единственная нежелательная часть - «Линия курса». Так как это также включено в

, поэтому оно также поступает в вывод. Тем не менее, я заметил, что у него есть дополнительный атрибут, то есть «colspan». Как я могу использовать его в качестве фильтра, чтобы «Линия заголовка» не отображалась на выходе.

Ответы [ 2 ]

3 голосов
/ 11 апреля 2020

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

for p in soup('tr')[1:]:
    print(p.text)

Пожалуйста, просмотрите эту запись для получения дополнительной информации о обозначении среза.

0 голосов
/ 11 апреля 2020

Исходя из ответа выше, вот код, который я сейчас использую:

response = requests.get(url_fii, headers=headers)
response.encoding = 'utf-8'
soup = BeautifulSoup(response.text,'lxml')

for p in soup('tr')[1:]:
    binNames = p.find_all('th')
    binValues = p.find_all('td')
    nBins = 0
    nValues = 0

    #The below section is for calculating the size of binNames. I didn't know of a better way than this.    
    for i in binNames:
            if len(i) > 0:
                nBins += 1

    #Now we print the binNames
    if nBins > 0:
        for i in range(nBins):
            print(binNames[i].text)

    #The below section is for calculating the size of binValues. I didn't know of a better way than this. 
    for i in binValues:
            if len(i) > 0:
                nValues += 1

    #Now we print the binValues
    if nValues > 0:
        for i in range(nValues):
            print(binValues[i].text)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...