0
# News Search
1
2
Searches for news articles using DuckDuckGo's news search with time-based filtering and regional settings, returning structured news data with publication dates and source information.
3
4
## Capabilities
5
6
### News Search Function
7
8
Searches for news articles using specified keywords with filtering and configuration options.
9
10
```python { .api }
11
def news(
12
keywords: str,
13
region: str = "us-en",
14
safesearch: str = "moderate",
15
timelimit: str | None = None,
16
max_results: int | None = None,
17
) -> list[dict[str, str]]:
18
"""
19
DuckDuckGo news search. Query params: https://duckduckgo.com/params.
20
21
Parameters:
22
- keywords (str): Search keywords/query terms
23
- region (str): Region code (us-en, uk-en, ru-ru, etc.). Defaults to "us-en".
24
- safesearch (str): Safety filter level ("on", "moderate", "off"). Defaults to "moderate".
25
- timelimit (str, optional): Time filter ("d", "w", "m" for day, week, month). Defaults to None.
26
- max_results (int, optional): Maximum number of results to return. If None, returns results from first response only. Defaults to None.
27
28
Returns:
29
List of dictionaries with news search results containing:
30
- "date" (str): Publication date in ISO format (YYYY-MM-DDTHH:MM:SS)
31
- "title" (str): Article headline/title
32
- "body" (str): Article excerpt/summary
33
- "url" (str): Article URL
34
- "image" (str): Article image URL (may be None)
35
- "source" (str): News source/publication name
36
37
Raises:
38
- DuckDuckGoSearchException: Base exception for search errors
39
- RatelimitException: API request rate limit exceeded
40
- TimeoutException: Request timeout occurred
41
"""
42
```
43
44
### Usage Examples
45
46
Basic news search:
47
48
```python
49
from duckduckgo_search import DDGS
50
51
with DDGS() as ddgs:
52
news = ddgs.news("artificial intelligence")
53
for article in news:
54
print(f"Title: {article['title']}")
55
print(f"Date: {article['date']}")
56
print(f"Source: {article['source']}")
57
print(f"Summary: {article['body']}")
58
print(f"URL: {article['url']}")
59
if article['image']:
60
print(f"Image: {article['image']}")
61
print("---")
62
```
63
64
News search with time filter:
65
66
```python
67
from duckduckgo_search import DDGS
68
69
with DDGS() as ddgs:
70
# Search for recent news from the past day
71
news = ddgs.news(
72
keywords="climate change",
73
region="us-en",
74
safesearch="moderate",
75
timelimit="d", # Past day
76
max_results=15
77
)
78
79
print(f"Found {len(news)} recent articles about climate change")
80
81
for article in news:
82
print(f"\nTitle: {article['title']}")
83
print(f"Published: {article['date']}")
84
print(f"Source: {article['source']}")
85
print(f"Summary: {article['body'][:200]}...") # Truncate long summaries
86
print(f"Read more: {article['url']}")
87
```
88
89
Regional news search:
90
91
```python
92
from duckduckgo_search import DDGS
93
94
with DDGS() as ddgs:
95
# Search for technology news in different regions
96
regions = [
97
("us-en", "United States"),
98
("uk-en", "United Kingdom"),
99
("au-en", "Australia"),
100
("de-de", "Germany")
101
]
102
103
for region_code, region_name in regions:
104
print(f"\n=== Technology News from {region_name} ===")
105
106
news = ddgs.news(
107
keywords="technology innovation",
108
region=region_code,
109
timelimit="w", # Past week
110
max_results=5
111
)
112
113
for article in news:
114
print(f"• {article['title']} ({article['source']})")
115
print(f" {article['date']} - {article['url']}")
116
```
117
118
News search with filtering and processing:
119
120
```python
121
from duckduckgo_search import DDGS
122
from datetime import datetime, timezone
123
from collections import defaultdict
124
125
with DDGS() as ddgs:
126
news = ddgs.news("space exploration", max_results=30)
127
128
# Group articles by source
129
by_source = defaultdict(list)
130
for article in news:
131
by_source[article['source']].append(article)
132
133
print("Articles by source:")
134
for source, articles in by_source.items():
135
print(f"\n{source} ({len(articles)} articles):")
136
for article in articles:
137
print(f" • {article['title']}")
138
print(f" {article['date']}")
139
140
# Find most recent articles
141
print("\n=== Most Recent Articles ===")
142
sorted_news = sorted(news, key=lambda x: x['date'], reverse=True)
143
144
for article in sorted_news[:5]:
145
print(f"\n{article['title']}")
146
print(f"Published: {article['date']}")
147
print(f"Source: {article['source']}")
148
print(f"Summary: {article['body']}")
149
```
150
151
News search with image filtering:
152
153
```python
154
from duckduckgo_search import DDGS
155
156
with DDGS() as ddgs:
157
news = ddgs.news("sports championship", max_results=20)
158
159
# Filter articles that have images
160
articles_with_images = [article for article in news if article['image']]
161
162
print(f"Found {len(articles_with_images)} articles with images out of {len(news)} total")
163
164
for article in articles_with_images:
165
print(f"\nTitle: {article['title']}")
166
print(f"Source: {article['source']}")
167
print(f"Date: {article['date']}")
168
print(f"Image: {article['image']}")
169
print(f"Article: {article['url']}")
170
```
171
172
### Error Handling
173
174
Handle news search errors:
175
176
```python
177
from duckduckgo_search import DDGS
178
from duckduckgo_search.exceptions import (
179
DuckDuckGoSearchException,
180
RatelimitException,
181
TimeoutException
182
)
183
184
try:
185
with DDGS() as ddgs:
186
news = ddgs.news("breaking news", max_results=50)
187
print(f"Retrieved {len(news)} news articles")
188
189
# Validate news data
190
for article in news:
191
required_fields = ['date', 'title', 'body', 'url', 'source']
192
missing_fields = [field for field in required_fields if not article.get(field)]
193
194
if missing_fields:
195
print(f"Article missing fields {missing_fields}: {article.get('title', 'No title')}")
196
else:
197
print(f"Valid article: {article['title']} from {article['source']}")
198
199
except RatelimitException as e:
200
print(f"Rate limit exceeded: {e}")
201
# Implement retry with exponential backoff
202
203
except TimeoutException as e:
204
print(f"Request timed out: {e}")
205
# Retry with increased timeout
206
207
except DuckDuckGoSearchException as e:
208
print(f"News search error: {e}")
209
```
210
211
### Advanced Usage
212
213
Date parsing and analysis:
214
215
```python
216
from duckduckgo_search import DDGS
217
from datetime import datetime, timezone
218
import json
219
220
with DDGS() as ddgs:
221
news = ddgs.news("economy", max_results=25)
222
223
# Parse and analyze publication dates
224
parsed_dates = []
225
for article in news:
226
try:
227
# Parse ISO format date
228
date_obj = datetime.fromisoformat(article['date'].replace('Z', '+00:00'))
229
parsed_dates.append({
230
'title': article['title'],
231
'source': article['source'],
232
'date': date_obj,
233
'url': article['url']
234
})
235
except ValueError as e:
236
print(f"Could not parse date '{article['date']}': {e}")
237
238
# Sort by date and find date range
239
if parsed_dates:
240
sorted_articles = sorted(parsed_dates, key=lambda x: x['date'])
241
oldest = sorted_articles[0]['date']
242
newest = sorted_articles[-1]['date']
243
244
print(f"Articles span from {oldest} to {newest}")
245
print(f"Most recent: {sorted_articles[-1]['title']} ({sorted_articles[-1]['source']})")
246
print(f"Oldest: {sorted_articles[0]['title']} ({sorted_articles[0]['source']})")
247
```
248
249
Export news data:
250
251
```python
252
from duckduckgo_search import DDGS
253
import json
254
import csv
255
256
with DDGS() as ddgs:
257
news = ddgs.news("renewable energy", max_results=20)
258
259
# Export to JSON
260
with open('news_results.json', 'w', encoding='utf-8') as f:
261
json.dump(news, f, indent=2, ensure_ascii=False)
262
263
# Export to CSV
264
with open('news_results.csv', 'w', newline='', encoding='utf-8') as f:
265
fieldnames = ['date', 'title', 'body', 'url', 'image', 'source']
266
writer = csv.DictWriter(f, fieldnames=fieldnames)
267
writer.writeheader()
268
writer.writerows(news)
269
270
print(f"Exported {len(news)} articles to JSON and CSV")
271
```
272
273
## Parameter Details
274
275
### Time Limits
276
- `"d"`: Past day - Most recent news from the last 24 hours
277
- `"w"`: Past week - News from the last 7 days
278
- `"m"`: Past month - News from the last 30 days
279
280
### SafeSearch Options
281
- `"on"`: Strict filtering, blocks potentially sensitive content
282
- `"moderate"`: Moderate filtering (default)
283
- `"off"`: No filtering
284
285
### Region Codes
286
Common region codes for localized news results:
287
- `"us-en"`: United States (English)
288
- `"uk-en"`: United Kingdom (English)
289
- `"au-en"`: Australia (English)
290
- `"ca-en"`: Canada (English)
291
- `"de-de"`: Germany (German)
292
- `"fr-fr"`: France (French)
293
- `"ru-ru"`: Russia (Russian)
294
- `"jp-jp"`: Japan (Japanese)
295
- `"cn-zh"`: China (Chinese)
296
- `"in-en"`: India (English)
297
298
## Data Format
299
300
### Date Format
301
News article dates are returned in ISO 8601 format:
302
- Format: `YYYY-MM-DDTHH:MM:SS` (UTC timezone)
303
- Example: `"2023-12-07T14:30:45"`
304
305
### Article Fields
306
Each news result contains:
307
- **date**: ISO formatted publication timestamp
308
- **title**: Article headline (string)
309
- **body**: Article excerpt/summary (string, may be lengthy)
310
- **url**: Full article URL (string)
311
- **image**: Article image URL (string or None)
312
- **source**: Publication/website name (string)
313
314
### Image Availability
315
Not all news articles include images. Check if `article['image']` is not None before using image URLs.