簡體   English   中英

使用 Python 中的 NewsPaper 庫將新聞文章抓取到一個列表中?

[英]Scraping news articles into one single list with NewsPaper library in Python?

親愛的 Stackoverflow 社區!

我想從 CNN RSS 提要中抓取新聞文章並獲取每篇抓取文章的鏈接。 這適用於 Python NewsPaper 庫,但不幸的是,我無法以可用格式(即列表或字典)獲得 output。

我想將抓取的鏈接添加到一個 SINGLE 列表中,而不是許多單獨的列表中。

    import feedparser as fp
    import newspaper
    from newspaper import Article

    website = {"cnn": {"link": "http://edition.cnn.com/", "rss": "http://rss.cnn.com/rss/cnn_topstories.rss"}}

    for source, value in website.items():
        if 'rss' in value:
            d = fp.parse(value['rss']) 
            #if there is an RSS value for a company, it will be extracted into d

            for entry in d.entries:
                if hasattr(entry, 'published'):
                    article = {}
                    article['link'] = entry.link
                    print(article['link'])

output如下:

http://rss.cnn.com/~r/rss/cnn_topstories/~3/5aHaFHz2VtI/index.html
http://rss.cnn.com/~r/rss/cnn_topstories/~3/_O8rud1qEXA/joe-walsh-trump-gop-voters-sot-crn-vpx.cnn
http://rss.cnn.com/~r/rss/cnn_topstories/~3/xj-0PnZ_LwU/index.html
.......

我想要一個包含所有鏈接的列表,即:

    list =[http://rss.cnn.com/~r/rss/cnn_topstories/~3/5aHaFHz2VtI/index.html , http://rss.cnn.com/~r/rss/cnn_topstories/~3/_O8rud1qEXA/joe-walsh-trump-gop-voters-sot-crn-vpx.cnn , http://rss.cnn.com/~r/rss/cnn_topstories/~3/xj-0PnZ_LwU/index.html ,... ]

我嘗試通過 for 循環附加內容,如下所示:

    for i in article['link']:
        article_list = []
        article_list.append(i)
        print(article_list)

但是output是這樣的:

['h']
['t']
['t']
['p']
[':']
['/']
['/']
['r']
['s']
...

有誰知道另一種方法,如何將內容放入一個列表中? 或者一個字典如下:

    dict = {'links':[link1 , link2 , link 3]}

非常感謝您的幫助!!

嘗試像這樣修改您的代碼,看看它是否有效:

article_list = []
for entry in d.entries:
            if hasattr(entry, 'published'):
                article = {}
                article['link'] = entry.link
                article_list.append(article['link'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM