alex.bergandine
alex.bergandine

Reputation: 75

Python Web Scraping Error TypeError: 'int' object is not iterable

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!

Upvotes: 0

Views: 302

Answers (2)

jGuille97
jGuille97

Reputation: 9

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.

Upvotes: -1

SimonR
SimonR

Reputation: 1824

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)

Upvotes: 2

Related Questions