要编写一个Python RPA(Robotic Process Automation)程序来实现每天中午12点定时打开今日头条并获取最新前五条新闻标题和内容,然后保存到txt文件中,你可以使用以下步骤和库来完成:
- 安装必要的库: 你需要安装以下库来实现这个任务:schedule:用于定时执行任务。selenium:用于自动化浏览器操作。chromedriver-autoinstaller:用于自动安装 Chrome 驱动程序。pyperclip:用于复制文本到剪贴板。time:用于添加一些延迟以确保页面加载完整。
你可以使用以下命令来安装这些库:
pip install schedule
pip install selenium
pip install chromedriver-autoinstaller
pip install pyperclip
import schedule
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import pyperclip
# 定义获取新闻的函数
def get_top_news():
# 初始化 Chrome 浏览器
chrome_service = Service("path/to/chromedriver")
driver = webdriver.Chrome(service=chrome_service)
# 打开今日头条网站
driver.get("https://www.toutiao.com/")
# 等待页面加载(你可以根据需要调整等待时间)
time.sleep(5)
# 使用 ActionChains 模拟按下 Ctrl + End 键,确保页面加载完整
ActionChains(driver).key_down(Keys.CONTROL).send_keys(Keys.END).key_up(Keys.CONTROL).perform()
time.sleep(5)
# 获取前五条新闻标题和内容
news_elements = driver.find_elements(By.CSS_SELECTOR, "div.card-news")
top_news = []
for element in news_elements[:5]:
title = element.find_element(By.CSS_SELECTOR, "div.title").text
content = element.find_element(By.CSS_SELECTOR, "div.abstract").text
top_news.append(f"标题: {title}\n内容: {content}\n")
# 关闭浏览器
driver.quit()
# 将新闻信息保存到txt文件中
with open("top_news.txt", "w", encoding="utf-8") as file:
file.writelines(top_news)
# 创建定时任务,每天中午12点执行
schedule.every().day.at("12:00").do(get_top_news)
# 启动定时任务
while True:
schedule.run_pending()
time.sleep(1)
确保替换上述脚本中的 "path/to/chromedriver" 为你的 Chrome 驱动程序的路径。
这个脚本将在每天中午12点打开今日头条,获取前五条新闻的标题和内容,并将它们保存到名为 "top_news.txt" 的文本文件中。你可以使用计划任务或类似的方式来定期运行这个脚本。确保你的计算机在计划任务运行时处于开启状态。