需求:python采集头条热搜词并自动去重保存为txt文件,服务器可以加一个定时采集脚本,就会一直采集头条热搜词,把第一版的脚本用类封装起来。
import requests import json class ToutiaoHotTopicsScraper: def __init__(self, url, filename): self.url = url self.filename = filename def scrape_and_update_file(self): # 请求页面并解析出今日头条热榜的内容 response = requests.get(self.url) data = json.loads(response.text) titles = [item['Title'] for item in data['data']] # 打开现有的文件并读取已存在的标题 try: with open(self.filename, 'a+', encoding='utf-8') as f: f.seek(0) # 把文件指针移到文件开头 lines = f.readlines() # 读取所有行 existed_titles = set(line.strip() for line in lines) # 把已存在的标题做成集合 # 追加新的标题到文件末尾,同时去重 for title in titles: if title not in existed_titles: # 如果标题不存在于已存在的集合中,就追加到文件末尾 f.write(title + '\n') existed_titles.add(title) print(f"内容已成功添加到文件 {self.filename} 并排重。") except Exception as e: print(f"保存文件时出现错误: {e}") if __name__ == "__main__": url = "https://api.toutiaoapi.com/hot-event/hot-board/?origin=hot_board" filename = "toutiaoresou.txt" scraper = ToutiaoHotTopicsScraper(url, filename) scraper.scrape_and_update_file()