import requests import parsel import csv with open("data.csv", mode="a", encoding="utf-8", newline="") as f: csv_writer = csv.DictWriter(f, fieldnames=["排名", "名字", "球队", "得分", "场次"]) if f.tell() == 0: csv_writer.writeheader() url = "https://nba.hupu.com/stats/players" response = requests.get(url=url) html_data = response.text selector = parsel.Selector(html_data) trs = selector.xpath('//tbody/tr[position()>1]') for tr in trs: ranking = tr.xpath("./td[1]/text()").get() name = tr.xpath("./td[2]//a/text()").get() team = tr.xpath("./td[3]//a/text()").get() score = tr.xpath("./td[4]/text()").get() venue = tr.xpath("./td[11]/text()").get() print(f"排名: {ranking}, 名字: {name}, 球队: {team}, 得分: {score}, 场次: {venue}") data_dict = { "排名": ranking, "名字": name, "球队": team, "得分": score, "场次": venue } csv_writer.writerow(data_dict)