soup = BeautifulSoup(html_page, "html.parser")
tables = soup.find_all("table",{"class":"wikitable sortable"})
headers = ['month','day','movie','director','cast','producer','reference']
movie_tables = []
total_movies = 0
for table in tables:
caption = table.find("caption")
if not caption or not caption.get_text().strip():
movie_tables.append(table)
#captions = soup.find_all("caption")
max_columns = len(headers)
# List to store dictionaries
data_dict_list = []
movies= []
for movie_table in movie_tables:
table_rows = movie_table.find("tbody").find_all("tr")[1:]
for table_row in table_rows:
total_movies += 1
columns = table_row.find_all('td')
row_data = [col.get_text(strip=True) for col in columns]
# If the row has fewer columns than the max, pad it with None
if len(row_data) == 6:
row_data.insert(0, None)
elif len(row_data) == 5:
row_data.insert(0, None)
row_data.insert(1, None)
for col in columns:
li_tags = col.find_all('li')
if li_tags:
cast=""
for li in li_tags:
li_values = li.get_text(strip=True)
cast = ', '.join(li_values)
row_data.append(cast)
else:
row_data.append(col.get_text())
# Create a dictionary mapping headers to row data
row_dict = dict(zip(headers, row_data))
# Append the dictionary to the list
data_dict_list.append(row_dict)
# Print the list of dictionaries
for row_dict in data_dict_list:
print(row_dict)
Вот что я получаю (здесь просто показываю несколько элементов):
[url=/wiki/Mythri_Movie_Makers]Mythri Movie Makers[/url]
[url=#cite_note-185][183][/url]
[/code] Это мой скрипт Python, который я написал: [code]soup = BeautifulSoup(html_page, "html.parser")
tables = soup.find_all("table",{"class":"wikitable sortable"}) headers = ['month','day','movie','director','cast','producer','reference'] movie_tables = [] total_movies = 0 for table in tables: caption = table.find("caption") if not caption or not caption.get_text().strip(): movie_tables.append(table)
#captions = soup.find_all("caption")
max_columns = len(headers)
# List to store dictionaries data_dict_list = []
movies= [] for movie_table in movie_tables: table_rows = movie_table.find("tbody").find_all("tr")[1:] for table_row in table_rows: total_movies += 1 columns = table_row.find_all('td') row_data = [col.get_text(strip=True) for col in columns] # If the row has fewer columns than the max, pad it with None if len(row_data) == 6: row_data.insert(0, None) elif len(row_data) == 5: row_data.insert(0, None) row_data.insert(1, None) for col in columns: li_tags = col.find_all('li') if li_tags: cast="" for li in li_tags: li_values = li.get_text(strip=True) cast = ', '.join(li_values)
row_data.append(cast) else: row_data.append(col.get_text()) # Create a dictionary mapping headers to row data row_dict = dict(zip(headers, row_data))
# Append the dictionary to the list data_dict_list.append(row_dict)
# Print the list of dictionaries for row_dict in data_dict_list: print(row_dict) [/code] Вот что я получаю (здесь просто показываю несколько элементов): [code]{'month': 'OCT', 'day': '11', 'movie': 'Viswam', 'director': 'Sreenu Vaitla', 'cast': 'GopichandKavya ThaparVennela KishoreSunilNaresh', 'producer': 'Chitralayam StudiosPeople Media Factory', 'reference': '[178]'}
{'month': None, 'day': '20', 'movie': 'Robinhood', 'director': 'Venky Kudumula', 'cast': 'NithiinSreeleela', 'producer': 'Mythri Movie Makers', 'reference': '[183]'} [/code] Вот что я пытаюсь получить (просто показываю здесь последний элемент): [code]{'month': 'DEC', 'day': '20', 'movie': 'Robinhood', 'director': 'Venky Kudumula', 'cast': 'Nithiin|Sreeleela', 'producer': 'Mythri Movie Makers', 'reference': '[183]'} [/code] Я пытался отладить это в течение последнего дня или около того, но не могу понять, где я ошибся. Я ожидаю: [list] [*]месяц и день заполняются во всех элементах, если эти столбцы занимают несколько строк и не представлены во всех строках. [*]Далее я хочу иметь разделитель между различными актерами, чтобы мне было легче позже создать график. [*]Кроме того, как мне извлечь гиперссылки и хранить в отдельном ключе в словаре и при этом все это делать? [/list]