报馆

2024-03-28 22:15:23 发布

您现在位置:Python中文网/ 问答频道 /正文

作为一个使用python主题的新手,我在使用报纸库扩展时遇到了一些困难。我的目标是定期使用报纸扩展来下载一个名为“Tageschau”的德国新闻网站的所有新文章和CNN的所有文章,以建立一个我可以在几年内分析的数据堆栈。 如果我做得对,我可以使用以下命令将所有文章下载到python库中。在

import newspaper
from newspaper import news_pool

tagesschau_paper = newspaper.build('http://tagesschau.de')
cnn_paper = newspaper.build('http://cnn.com')

papers = [tagesschau_paper, cnn_paper]
news_pool.set(papers, threads_per_source=2) # (3*2) = 6 threads total
news_pool.join()`

如果这是下载所有文章的正确方法,那么我如何在python之外提取和保存这些文章呢?或者将这些文章保存在python中,以便在重新启动python时可以重用它们?在

谢谢你的帮助。在


Tags: importbuildhttp主题文章newspapercnnpaper
2条回答

您可以使用pickle在python之外保存对象,并在以后重新打开它们:

file_Name = "testfile"
# open the file for writing
fileObject = open(file_Name,'wb') 

# this writes the object news_pool to the
# file named 'testfile'
pickle.dump(news_pool,fileObject)   

# here we close the fileObject
fileObject.close()
# we open the file for reading
fileObject = open(file_Name,'r')  
# load the object from the file into var news_pool_reopen
news_pool_reopen = pickle.load(fileObject)  

以下代码将以HTML格式保存下载的文章。在文件夹中,你会发现。tagesschau_paper0.html, tagesschau_paper1.html, tagesschau_paper2.html, .....

import newspaper
from newspaper import news_pool

tagesschau_paper = newspaper.build('http://tagesschau.de')
cnn_paper = newspaper.build('http://cnn.com')

papers = [tagesschau_paper, cnn_paper]
news_pool.set(papers, threads_per_source=2)
news_pool.join()

for i in range (tagesschau_paper.size()): 
    with open("tagesschau_paper{}.html".format(i), "w") as file:
    file.write(tagesschau_paper.articles[i].html)

注意:news_pool没有从CNN得到任何东西,所以我跳过了为它编写代码。如果选中cnn_paper.size(),结果是0。您必须导入并使用Source。在

你也可以按照上面的格式发表文章,例如,以其他格式发表文章。在

相关问题 更多 >