У меня есть следующий python скрипт
from bs4 import BeautifulSoup
import requests
home_dict = []
for year in range(2005, 2021):
if year == 2020:
for month in range(1, 6):
url = 'https://www.rebgv.org/market-watch/MLS-HPI-home-price-comparison.hpi.all.all.' + str(year) + '-' + str(month) + '-1.html';
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
home_table = soup.find('div', class_="table-wrapper")
for home in home_table.find_all('tbody'):
rows = home.find_all('tr')
for row in rows:
area = row.find('td').text;
benchmark = row.find_all('td')[1].text
priceIndex = row.find_all('td')[2].text
oneMonthChange = row.find_all('td')[3].text
sixMonthChange = row.find_all('td')[4].text
oneYearChange = row.find_all('td')[5].text
threeYearChange = row.find_all('td')[6].text
fiveYearChange = row.find_all('td')[7].text
propertyType = row.find_all('td')[8].text
year = year;
month = month;
home_obj = {
"Area": area,
"Benchmark": benchmark,
"Price Index": priceIndex,
"1 Month +/-": oneMonthChange,
"6 Month +/-": sixMonthChange,
"1 Year +/-": oneYearChange,
"3 Year +/-": threeYearChange,
"5 Year +/-": fiveYearChange,
"Property Type": propertyType,
"Report Month": month,
"Report Year": year
}
home_dict.append(home_obj)
else:
for month in range(1, 13):
url = 'https://www.rebgv.org/market-watch/MLS-HPI-home-price-comparison.hpi.all.all.' + str(year) + '-' + str(month) + '-1.html';
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
home_table = soup.find('div', class_="table-wrapper")
for home in home_table.find_all('tbody'):
rows = home.find_all('tr')
for row in rows:
area = row.find('td').text;
benchmark = row.find_all('td')[1].text
priceIndex = row.find_all('td')[2].text
oneMonthChange = row.find_all('td')[3].text
sixMonthChange = row.find_all('td')[4].text
oneYearChange = row.find_all('td')[5].text
threeYearChange = row.find_all('td')[6].text
fiveYearChange = row.find_all('td')[7].text
propertyType = row.find_all('td')[8].text
year = year;
month = month;
home_obj = {
"Area": area,
"Benchmark": benchmark,
"Price Index": priceIndex,
"1 Month +/-": oneMonthChange,
"6 Month +/-": sixMonthChange,
"1 Year +/-": oneYearChange,
"3 Year +/-": threeYearChange,
"5 Year +/-": fiveYearChange,
"Property Type": propertyType,
"Report Month": month,
"Report Year": year
}
home_dict.append(home_obj)
print(home_dict)
Этот скрипт выполняет парсинг веб-сайта. Если сейчас 2020 год, это будет только с января по май. В другие годы это будет go с января по De c.
Вы можете сказать, что тело сценария повторяется внутри этого условного оператора if-else, есть ли более простой способ написать это чтобы он выглядел чище и не повторялся?