【问题标题】:Python Web Scraping Error TypeError: 'int' object is not iterablePython Web Scraping Error TypeError: 'int' object is not iterable
【发布时间】:2020-11-07 19:09:42
【问题描述】:

我一直在尝试修改我发现的一个程序,它可以为您提供三个随机的头条新闻。代码如下:

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

希望有人能帮忙谢谢!

【问题讨论】:

标签: python beautifulsoup int typeerror


【解决方案1】:

random.choice 只返回一个元素。然后,你有 for news_list in range(3) ,所以 news_list 这里只是一个整数。您希望random.choices(注意's')的参数为3,并迭代这些:

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)

【讨论】:

    【解决方案2】:

    当你这样做时:

    news_list = random.choice(news_list)
    

    random.choice 函数返回数组、列表或序列的单个元素。在这种情况下,news_list 上的一个元素。 在这一行之后,news_list 的新值是一个元素,检查你得到的错误,是一个 int 变量,它不能通过 for 迭代。

    【讨论】:

      猜你喜欢
      • 2019-04-12
      • 1970-01-01
      • 2021-08-08
      • 2016-02-18
      • 2022-11-02
      • 2018-06-29
      • 2016-01-09
      • 2018-12-10
      • 2022-12-15
      相关资源
      最近更新 更多