Python BeautifulSoup - устраняет проблемы при разборе таблицы и избегает нежелательных строк - PullRequest
0 голосов
/ 09 ноября 2019

Я пытаюсь проанализировать данные таблицы из этой википедии страница для проекта Django.

Пользователь выбирает, какой период времени он хочет просмотреть (переменная века), и возвращаетзапрашиваемая информация Имя , Изображение и Обозначение в таблице.

В некоторых вики-таблицах в середине есть заголовки, которые я стараюсь избегать в своей таблице.

Я все еще новичок в Python и BeautifulSoup может показаться, что я делаю это нелегко. Как получить текст из столбцов Имя и Обозначение , а также изображение из столбца Изображение и избежать анализа заголовков в здесь .


import requests
from bs4 import BeautifulSoup
import pandas as pd

getPage = requests.get("https://en.wikipedia.org/wiki/Timeline_of_discovery_of_Solar_System_planets_and_their_moons")

source = getPage.content
soup = BeautifulSoup(source, 'html.parser')
discoverTable = soup.find(id = century).findNext('table', {"class" : "wikitable"})

create_table = [['Name', 'Image', 'Designation']]
Prehistory_rows = discoverTable.find_all('tr')[2:]
rows = discoverTable.find_all('tr')[3:]

for row in Prehistory_rows:
    if century in ('Prehistory'):
        name_cell = row.find_all('td')[0].get_text()
        image_cell = row.find_all('td')[1]
        designation_cell = row.find_all('td')[2].get_text()
        display_info = [name_cell, image_cell, designation_cell]
        create_table.append(display_info)

for row in rows:
    if century in ('17th_century','18th_century','19th_century','1901-1950'):
        first_cell = row.find_all('td')[0]
        if first_cell.has_attr('colspan'):
            row.decompose() 
        if first_cell.has_attr('rowspan'):
            spanLength = int(first_cell['rowspan'])
            for i in range(1,spanLength+1):
                for row in rows:
                    name_cell = row.find_all('td')[0].get_text()
                    image_cell = row.find_all('td')[1]
                    designation_cell = row.find_all('td')[2].get_text()
                    display_info = [name_cell, image_cell, designation_cell]
                    create_table.append(display_info) # add rows to the table

        else:
            first_cell = row.find_all('td')[0]
            name_cell = row.find_all('td')[1].get_text()
            image_cell = row.find_all('td')[2]
            designation_cell = row.find_all('td')[3].get_text()
            display_info = [name_cell, image_cell, designation_cell] 
            create_table.append(display_info) # add rows to the table


df = pd.DataFrame(create_table[1:], columns = create_table[0])
tabledata = df.to_html(escape = False, classes='discoverTable', index=False)

context = {
    'tabledata' : tabledata,
    'century' : century,
}

return render(request, 'discoveryTimeline/discovery_result.html', context)

...