So, my objective with this code is extract information about a rookie in my NFL team. I want to compare his performance with players that finished last season in top-10 statistics in his position when they were in first season where they played more than 10 games.
For that, I used as reference a post in Towards Data Science, where they explained how to scrape NFL data.
Here is my code:
#url page
url_mac = 'https://www.pro-football-reference.com/years/2021/passing.htm'
#opening URL with BS
html_mac = urlopen(url_mac)
stats_macpage = BeautifulSoup(html_mac)
#collecting table rows
column_headers = stats_macpage.findAll('tr')[0]
column_headers = [i.getText() for i in column_headers.findAll('th')]
#getting stats of each row
rows = stats_macpage.findAll('tr')[1:]
qb_stats = []
for i in range(len(rows)):
qb_stats.append([col.getText() for col in rows[i].findAll('td')])
#creating a data frame
data = pd.DataFrame(qb_stats, columns = column_headers[1:])
#rename column of sack yards from yards to y_sack
new_columns = data.columns.values
new_columns[-6] = 'y_sack'
data.columns = new_columns
#selecting specifics stats
categories = ['Cmp%', 'Yds', 'TD', 'Int', 'Y/A', 'Rate']
#first filter
data_radar = data[['Player', 'Tm'] + categories]
#selecting specific player
data_mac = data_radar[data_radar['Player'] == 'Mac Jones']
I did it for all 11 players that I want the data and I had concatenated in the final, but you can imagine how bad my code is looking.
How can I improve it to create a loop ? I already tried some things, but for all of these ideas, either they didn't work well or were beyond my capabilities to execute successfully.
Between my ideas was take all data of the last 20 years and try find year by year, but that look a bit unnecessary, because I already know what years I want. My problem is specifically in this part, because in the final I could create a list and then an "if" and only take the first year of each player in my list played > 10 games.
url_mac = 'https://www.pro-football-reference.com/years/2021/passing.htm'
Thank you, all.

https://www.pro-football-reference.com/years/<YEAR>/passing.htmfor last 10 years and concatenate them to one?