【Python】抓取岭东资讯比赛成绩

import requests
from bs4 import BeautifulSoup
import csv
import re

base_url="http://china.530520.com.tw/msg/matchGameDetail.asp?Page={}&Ucgp=326&mID=431&mgID=1665"

发送GET请求获取网页内容,mgid为比赛编号,ucgp&mid这二个数字为俱乐部或公棚编号,想获取哪个俱乐部的数据自己去查一下。

rows = []
for i in range(50): #这是成绩总页码,可以根据情况自己调整。
url = base_url.format(i)
response = requests.get(url)
response.encoding = 'utf-8' # 设置编码,避免中文乱码

使用BeautifulSoup解析HTML

soup = BeautifulSoup(response.text, 'html.parser')

找到包含数据的表格

table = soup.find(name="table",attrs={'border': '0','cellpadding':'3'})

提取数据行

if i==0:
for tr in table.find_all('tr')[0:1]: # 跳过表头行
row=[]
for td in tr.find_all('td'):

移除括号中的内容

text = re.sub(r'[.*?]', '', td.text.strip())
row.append(text)
if row: # 确保行不为空
rows.append(row)
else:
for tr in table.find_all('tr')[1:]: # 跳过表头行
row=[]
for td in tr.find_all('td'):

移除括号中的内容

text = re.sub(r'[.*?]', '', td.text.strip())
row.append(text)
if row: # 确保行不为空
rows.append(row)

将数据写入CSV文件

with open('比赛数据.csv', 'w', newline='', encoding='utf-8-sig') as f:
writer = csv.writer(f)

writer.writerows(rows)

print("数据已成功抓取并保存到'比赛数据.csv'文件中。")