Для работы меня попросили создать электронную таблицу с именами и адресами всех аллопатических медицинских школ в Соединенных Штатах.Будучи новичком в python, я подумал, что это будет идеальная ситуация для того, чтобы попробовать очистку веб-страниц.Хотя в конце концов я написал программу, которая возвращала нужные мне данные, я знаю, что есть лучший способ сделать это, так как были некоторые посторонние символы (например: ",], [), которые мне пришлось перейти в Excel и удалить вручную.Я просто хотел бы знать, есть ли лучший способ, которым я мог бы написать этот код, чтобы я мог получить то, что мне нужно, за исключением посторонних символов.
Редактировать: я также приложил изображение файла CSV, которыйбыл создан, чтобы показать посторонние символы, о которых я говорю.
from bs4 import BeautifulSoup
import requests
import csv
link = "https://members.aamc.org/eweb/DynamicPage.aspx?site=AAMC&webcode=AAMCOrgSearchResult&orgtype=Medical%20School" # noqa
# link to the site we want to scrape from
page_response = requests.get(link)
# fetching the content using the requests library
soup = BeautifulSoup(page_response.text, "html.parser")
# Calling BeautifulSoup in order to parse our document
data = []
# Empty list for the first scrape. We only get one column with many rows.
# We still have the line break tags here </br>
for tr in soup.find_all('tr', {'valign': 'top'}):
values = [td.get_text('</b>', strip=True) for td in tr.find_all('td')]
data.append(values)
data2 = []
# New list that we'll use to have name on index i, address on index i+1
for i in data:
test = list(str(i).split('</b>'))
# Using the line breaks to our advantage.
name = test[0].strip("['")
'''Here we are saying that the name of the school is the first element
before the first line break'''
addy = test[1:]
# The address is what comes after this first line break
data2.append(name)
data2.append(addy)
# Append the name of the school and address to our new list.
school_name = data2[::2]
# Making a new list that consists of the school name
school_address = data2[1::2]
# Another list that consists of the school's address.
with open("Medschooltest.csv", 'w', encoding='utf-8') as toWrite:
writer = csv.writer(toWrite)
writer.writerows(zip(school_name, school_address))
'''Zip the two together making a 2 column table with the schools name and
it's address'''
print("CSV Completed!")
Создан файл CSV