我正在使用报纸3从news.google中提取网址,但问题是我不断获取所有网址(我已禁用memoize,因为我需要完整列表)。我只想打印前 5 个链接或 5 个随机链接并不重要。 我尝试过设置最大值,但没有成功。有什么想法吗?
import newspaper
news = newspaper.build('https://news.google.com/topics/CAAqJggKIiBDQkFTRWdvSUwyMHZNRGx6TVdZU0FtVnVHZ0pWVXlnQVAB?oc=3&ceid=US:en', memoize_articles=False)
for article in news.articles:
print(article.url)
最佳答案
这段代码应该正是您想要的。它不使用报纸功能,而是随机选择一定数量的网址。报纸的输出不是列表,因此必须使用追加函数将其转换为列表。享受吧!
import newspaper
business_news = newspaper.build('https://news.google.com/topics/CAAqJggKIiBDQkFTRWdvSUwyMHZNRGx6TVdZU0FtVnVHZ0pWVXlnQVAB?hl=en-US&gl=US&ceid=US%3Aen', language='en', memoize_articles = False)
myList = []
for article in business_news.articles:
myList.append(str(article.url))
print(myList) #not necessary just for display purposes
import random
aselect = myList
randarticles = random.sample(aselect, 5)
print(randarticles)
关于python - 限制报纸的 URL 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54945705/