爬取目标:
爬取结果如下:
代码如下:
import csv
import requests
from bs4 import BeautifulSoup
base_url = 'http://college.gaokao.com/areapoint/p'
total_pages = 222 # 总页数
# 创建CSV文件并写入表头
with open('data.csv', 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(['年份', '考生所在地', '文理分科', '批次名称', '最低控制分数线'])
for page in range(1, total_pages + 1):
url = base_url + str(page) + '/'
response = requests.get(url)
html_content = response.text
soup = BeautifulSoup(html_content, 'html.parser')
table_rows = soup.find_all('tr')
for row in table_rows:
cells = row.find_all('td')
if len(cells) == 5: # 确保行中包含所需的5个单元格
year = cells[0].text
location = cells[1].text
science_art = cells[2].text
batch_name = cells[3].text
min_score = cells[4].text
# 判断年份是否在指定范围内
if 2011 <= int(year) <= 2021:
# 写入提取的数据到CSV文件
writer.writerow([year, location, science_art, batch_name, min_score])
print("数据已保存到data.csv文件中")