How can I request the first 100 titles in NewsAPI instead of first one?

82 Views Asked by At

Here, the code returns the first article's title according to the search information

import requests

r = requests.get("https://newsapi.org/v2/everything?qInTitle=bangladesh&from=2023-07-17&to=2023-08-16&sortBy=popularity&language=en&apiKey=45c28deca60947fd9ec4d8db2b2c4a81")
content = r.json()

print(content['articles'][0]['title'])

How can I make it so that it returns the first 100 or something similar?

I've tried to remove the [0] and putting [0:100] instead but it didn't work; I am new to coding I apologize.

3

There are 3 best solutions below

0
Kaushal panchal On BEST ANSWER

You can do like this:

import requests

r = requests.get("https://newsapi.org/v2/everything?qInTitle=bangladesh&from=2023-07-17&to=2023-08-16&sortBy=popularity&language=en&apiKey=45c28deca60947fd9ec4d8db2b2c4a81")
content = r.json()

for row in content['articles'][:100]:
  print(row['title'])

0
Petəíŕd  The  Spring  Wizard On

You can use the for loop to iterate the first 100 elements (or rather "news"):

import requests

r = requests.get("https://newsapi.org/v2/everything?qInTitle=bangladesh&from=2023-07-17&to=2023-08-16&sortBy=popularity&language=en&apiKey=45c28deca60947fd9ec4d8db2b2c4a81")
content = r.json()

articles = content['articles']

for index in range(0, 99):
    print(articles[index]['title'])

I've put 99 because the array indexes is starting from 0 but not 1 and 100 - 1 is 99.

For each iteration, the print function will output the title of article with the index.

0
SIGHUP On

In order to acquire (up to) 100 titles then:

import requests

URL = 'https://newsapi.org/v2/everything'
PARAMS = {
    'qInTitle': 'bangladesh',
    'from': '2023-07-17',
    'to': '2023-08-16',
    'sortBy': 'popularity',
    'language': 'en',
    'apiKey': '45c28deca60947fd9ec4d8db2b2c4a81'
}
MAX = 100

with requests.get(URL, params=PARAMS) as response:
    response.raise_for_status()
    if (content := response.json()).get('status') == 'ok':
        for article in content.get('articles', [])[:MAX]:
            print(article.get('title'))

Output (partial):

Bangladesh grapples with record deadly outbreak of dengue fever - Reuters
Political party supporters, police clash in Bangladesh - Reuters
Bangladesh to tone down law critics accuse of crushing dissent - Reuters
Injured Tamim steps down as Bangladesh ODI captain, to miss Asia Cup - Reuters
...
Bangladesh dealing with worst dengue fever outbreak on record - Yahoo Canada Sports
WHO urges swift action as dengue cases surge in Bangladesh - Al Jazeera English
Boat carrying dozens sinks in Bangladesh capital Dhaka
UNICEF appeals for funding as record 300,000 children enrolled in Bangladesh Rohingya camps