python爬取多天新闻
时间: 2025-05-09 20:34:04 浏览: 15
### 实现连续多天新闻数据抓取
为了实现连续多天的新闻网页爬虫,可以基于 `threading.Thread` 类创建多个线程来进行并发操作[^1]。这有助于提高效率,尤其是在面对大量网页需要抓取的情况下。
对于长时间运行的任务来说,合理安排请求时间间隔至关重要。通过设置随机延时函数可以在一定程度上减少服务器压力以及避免被目标站点识别为恶意访问行为[^3]:
```python
import threading
from datetime import timedelta, date
import time
import random
import requests
def daterange(start_date, end_date):
for n in range(int((end_date - start_date).days)):
yield start_date + timedelta(n)
class NewsCrawler(threading.Thread):
def __init__(self, url_pattern, dates):
super().__init__()
self.url_pattern = url_pattern
self.dates = dates
def run(self):
for single_date in self.dates:
formatted_date = single_date.strftime("%Y-%m-%d")
target_url = self.url_pattern.format(date=formatted_date)
try:
fetch_with_delay(target_url)
except Exception as e:
print(f"Failed to fetch data from {target_url}: ", str(e))
def fetch_with_delay(url, delay_min=1, delay_max=3):
""" 发送请求并根据设定的时间间隔延迟 """
response = requests.get(url)
print(f"Request to {url} returned status code: {response.status_code}")
sleep_time = random.uniform(delay_min, delay_max) # 随机延迟
time.sleep(sleep_time)
start_date = date(2023, 9, 1)
end_date = date.today()
date_list = list(daterange(start_date, end_date))
num_threads = min(len(date_list), 5) # 控制最大线程数不超过5个
split_dates = [date_list[i::num_threads] for i in range(num_threads)]
threads = []
for idx in range(num_threads):
thread = NewsCrawler("http://news.example.com/archive?date={date}", split_dates[idx])
threads.append(thread)
thread.start()
for t in threads:
t.join() # 主程序等待所有子线程完成执行后再继续往下走
```
上述代码展示了如何构建一个多线程爬虫框架用于抓取指定日期范围内的新闻页面。这里定义了一个名为 `NewsCrawler` 的类继承自 `threading.Thread` ,并通过重写父类中的 `run()` 方法实现了具体的业务逻辑——即按照给定模式拼接URL并向其发出HTTP GET 请求;同时为了避免过快地向同一主机发送过多请求而触发反爬机制,加入了适当延时措施。
当涉及到具体某一天的具体新闻内容解析时,则可以根据实际情况选用合适的HTML 解析工具,比如 Beautiful Soup 或者 lxml 库来定位所需的信息片段[^4]。
阅读全文
相关推荐




















