0

I have been trying to modify a program I found that gives you three random top news headlines. Heres the code:

import bs4
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen
import random

news_url="https://news.google.com/news/rss"
Client=urlopen(news_url)
xml_page=Client.read()
Client.close()

soup_page=soup(xml_page,"xml")
news_list=soup_page.findAll("item")
# Print news title, url and publish date
news_list = random.choice(news_list)
for news_list in range(3):
    for news in news_list:
        print(news.title.text)
        print(news.link.text)
        print(news.pubDate.text)
        print("-"*60)

And heres the error I get with the code:

Traceback (most recent call last):
  File "newsstuff.py", line 16, in <module>
    for news in news_list:
TypeError: 'int' object is not iterable

I hope someone can help thanks!

2
  • Have you done any debugging? What do you understand from that error message? Commented Jul 18, 2020 at 0:06
  • Does this answer your question? Python - TypeError: 'int' object is not iterable Commented Jul 18, 2020 at 0:07

2 Answers 2

2

random.choice returns only one element. Then, you have for news_list in range(3) , so news_list here is just an integer. You want random.choices (note the 's') with an argument of 3, and to iterate over those:

news_list = random.choices(news_list, k=3)
for news in news_list:
    print(news.title.text)
    print(news.link.text)
    print(news.pubDate.text)
    print("-"*60)
Sign up to request clarification or add additional context in comments.

Comments

-1

when you do:

news_list = random.choice(news_list)

random.choice function return a single element of an array, list, or sequence. In this case an element on news_list. After this line the new value of news_list is a single element, checking the error that you're getting, is an int variable, which isn't iterable through a for.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.