reka-core-20240501· unknown
from LMArena Human Preference 100K
请写一个python代码,可以定时爬取特定网站的新闻内容
Private research annotation
Sign in to add a private research label or note.
- User
请写一个python代码,可以定时爬取特定网站的新闻内容
- Assistant
下面是一个使用Python的简单示例,使用
requests库获取网页内容和BeautifulSoup库解析HTML,结合schedule库来定时执行爬取任务。这个例子将定时爬取指定网站的新闻内容,并将标题和链接打印出来。首先,确保你已经安装了必要的库:
bashpip install requests beautifulsoup4 schedule然后,可以使用以下代码来实现定时爬取新闻的功能:
pythonimport requests from bs4 import BeautifulSoup import schedule import time def fetch_news(url): try: response = requests.get(url) response.raise_for_status() # 检查请求是否成功 soup = BeautifulSoup(response.text, 'html.parser') news_items = soup.find_all('div', class_='news-item') # 根据实际网页结构调整选择器 for item in news_items: title = item.find('h2').text link = item.find('a')['href'] print(f"Title: {title}\nLink: {link}\n") except requests.RequestException as e: print(f"Error fetching news: {e}") # 定义要爬取的网址 news_url = 'https://example.com/news' # 定义定时任务,每小时爬取一次 schedule.every(1).hours.do(fetch_news, news_url) while True: schedule.run_pending() time.sleep(1)在这个示例中,
fetch_news函数负责发送HTTP请求获取网页内容,使用BeautifulSoup解析HTML,并提取新闻标题和链接。schedule.every(1).hours.do()用于设置每小时运行一次fetch_news函数。while True循环确保程序持续运行并定时执行任务。请注意,你需要根据实际的网站结构调整
find_all和find方法的参数,以正确地提取新闻信息。不同的网站有不同的HTML结构,所以你可能需要查看目标网站的源代码来确定正确的选择器。