Python Web Scraping Error TypeError: 'int' object is not iterable
Python Web Scraping Error TypeError: 'int' object is not iterable
我一直在尝试修改我发现的一个程序,该程序可以为您提供三个随机的头条新闻。代码如下:
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)
这是我在代码中遇到的错误:
Traceback (most recent call last):
File "newsstuff.py", line 16, in <module>
for news in news_list:
TypeError: 'int' object is not iterable
希望有人能帮忙谢谢!
random.choice
returns只有一个元素。然后,你有 for news_list in range(3)
,所以 news_list
这里只是一个整数。你想要参数为 3 的 random.choices
(注意 's'),并迭代那些:
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)
当你这样做时:
news_list = random.choice(news_list)
random.choice 函数 return 数组、列表或序列的单个元素。在本例中,news_list 上的元素。
在这一行之后,news_list 的新值是单个元素,检查你得到的错误,是一个 int 变量,它不能通过 for.
迭代
我一直在尝试修改我发现的一个程序,该程序可以为您提供三个随机的头条新闻。代码如下:
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)
这是我在代码中遇到的错误:
Traceback (most recent call last):
File "newsstuff.py", line 16, in <module>
for news in news_list:
TypeError: 'int' object is not iterable
希望有人能帮忙谢谢!
random.choice
returns只有一个元素。然后,你有 for news_list in range(3)
,所以 news_list
这里只是一个整数。你想要参数为 3 的 random.choices
(注意 's'),并迭代那些:
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)
当你这样做时:
news_list = random.choice(news_list)
random.choice 函数 return 数组、列表或序列的单个元素。在本例中,news_list 上的元素。 在这一行之后,news_list 的新值是单个元素,检查你得到的错误,是一个 int 变量,它不能通过 for.
迭代