这里是新的编码员!我试图从多个URL中提取web表数据。每个URL网页都有一个表,但该表在多个页面中拆分。我的代码只遍历第一个URL的表页,而不遍历其余的表页。所以我只能得到2000年NBA数据的第1-5页,但就到此为止。如何让我的代码提取每年的数据?非常感谢您的帮助
page = 1
year = 2000
while page < 20 and year < 2020:
base_URL = 'http://www.espn.com/nba/salaries/_/year/{}/page/{}'.format(year,page)
response = requests.get(base_URL, headers)
if response.status_code == 200:
soup = BeautifulSoup(response.content, 'html.parser')
sal_table = soup.find_all('table', class_ = 'tablehead')
if len(sal_table) < 2:
sal_table = sal_table[0]
with open ('NBA_Salary_2000_2019.txt', 'a') as r:
for row in sal_table.find_all('tr'):
for cell in row.find_all('td'):
r.write(cell.text.ljust(30))
r.write('\n')
page+=1
else:
print("too many tables")
else:
year +=1
page = 1
我会考虑使用熊猫作为1)它是{{CD1>}函数(使用引擎盖下的漂亮汤),更容易解析^ {CD2>}标签,2)它可以很容易地直接写入文件。
也就是说,重复20页是一种浪费(例如,第一个赛季之后你只有4页……其余的都是空白的。所以我会考虑添加一些东西,比如一旦它到达空白表,就转到下一个赛季。
输出:
相关问题 更多 >
编程相关推荐