我正在使用报纸3从news.google提取URL,但是问题是我一直在获取所有URL(我已禁用备忘录功能,因为我需要完整列表)。我只想打印前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)
答案 0 :(得分:1)
此代码段应该正是您想要的。它不使用报纸功能,而是随机选择一定数量的网址。报纸的输出不是列表,因此必须使用append函数将其转换为列表。享受吧!
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)