如何从Google新闻RSS抓取Google新闻文章内容? [英] How to scrape Google News articles content from Google News RSS?

查看:373
本文介绍了如何从Google新闻RSS抓取Google新闻文章内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将来,(由于我仍然是新手,所以也许还很遥远)我想根据从Google新闻RSS获得的新闻内容进行数据分析,但为此,我需要访问该内容,这就是我的问题.

In the future, (maybe still far away, due to the fact that I'm still a novice) I want to do data analysis, based on the content of the news I get from the Google News RSS, but for that, I need to have access to that content, and that is my problem.

使用URL" https://news.google.cl/news/rss 我可以访问标题和每个新闻项的URL之类的数据,但该URL的格式不允许我抓取(

Using the URL "https://news.google.cl/news/rss" I have access to data like the title, and the URL of each news item, but the URL is in a format that does not allow me to scrape it (https://news.google.com/__i/rss/rd/articles/CBMilgFod...).

news_url="https://news.google.cl/news/rss"
Client=urlopen(news_url)
xml_page=Client.read()
Client.close()

soup_page=soup(xml_page,"xml")
news_list=soup_page.findAll("item")

for news in news_list:
    print(news.title.text)
    print("-"*60)

    response = urllib.request.urlopen(news.link.text)
    html = response.read()
    soup = soup(html,"html.parser")
    text = soup.get_text(strip=True)
    print(text) 

最后一个print(text)打印一些代码,例如:

The last print(text) prints some code like:

if(typeof bbclAM === 'undefined' || !bbclAM.isAM()) {
                        googletag.display('div-gpt-ad-1418416256666-0');
                } else {
                        document.getElementById('div-gpt-ad-1418416256666-0').st
yle.display = 'none'
                }
        });(function(s, p, d) {
            var h=d.location.protocol, i=p+"-"+s,
            e=d.getElementById(i), r=d.getElementById(p+"-root"),
            u=h==="https:"?"d1z2jf7jlzjs58.cloudfront.net"
            :"static."+p+".com";
            if (e) return;

我希望从RSS打印每个新闻的标题和内容

I expect to print the title and the content of each news item from the RSS

推荐答案

该脚本可以帮助您入门(从站点打印标题,URL,简短描述和内容).从网站解析内容是基本形式-每个网站都有不同的格式/样式等:

This script can get you something to start with (prints title, url, short description and content from the site). Parsing the content from the site is in basic form - each site has different format/styling etc. :

import textwrap
import requests
from bs4 import BeautifulSoup

news_url="https://news.google.cl/news/rss"
rss_text=requests.get(news_url).text
soup_page=BeautifulSoup(rss_text,"xml")

def get_items(soup):
    for news in soup.findAll("item"):
        s = BeautifulSoup(news.description.text, 'lxml')
        a = s.select('a')[-1]
        a.extract()         # extract lat 'See more on Google News..' link

        html = requests.get(news.link.text)
        soup_content = BeautifulSoup(html.text,"lxml")

        # perform basic sanitization:
        for t in soup_content.select('script, noscript, style, iframe, nav, footer, header'):
            t.extract()

        yield news.title.text.strip(), html.url, s.text.strip(), str(soup_content.select_one('body').text)

width = 80
for (title, url, shorttxt, content) in get_items(soup_page):
    title = '\n'.join(textwrap.wrap(title, width))
    url = '\n'.join(textwrap.wrap(url, width))
    shorttxt = '\n'.join(textwrap.wrap(shorttxt, width))
    content = '\n'.join(textwrap.wrap(textwrap.shorten(content, 1024), width))

    print(title)
    print(url)
    print('-' * width)
    print(shorttxt)
    print()
    print(content)
    print()

打印:

WWF califica como inaceptable y condenable adulteración de información sobre
salmones de Nova Austral - El Mostrador
https://m.elmostrador.cl/dia/2019/06/30/wwf-califica-como-inaceptable-y-
condenable-adulteracion-de-informacion-sobre-salmones-de-nova-austral/
--------------------------------------------------------------------------------
El MostradorLa organización pide investigar los centros de cultivo de la
salmonera de capitales noruegos y abrirá un proceso formal de quejas. La empresa
ubicada en la ...

01:41:28 WWF califica como inaceptable y condenable adulteración de información
sobre salmones de Nova Austral - El Mostrador País PAÍS WWF califica como
inaceptable y condenable adulteración de información sobre salmones de Nova
Austral por El Mostrador 30 junio, 2019 La organización pide investigar los
centros de cultivo de la salmonera de capitales noruegos y abrirá un proceso
formal de quejas. La empresa ubicada en la Patagonia chilena es acusada de
falsear información oficial ante Sernapesca. 01:41:28 Compartir esta Noticia
Enviar por mail Rectificar Tras una investigación periodística de varios meses,
El Mostrador accedió a abundante información reservada, que incluye correos
electrónicos de la gerencia de producción de la compañía salmonera Nova Austral
–de capitales noruegos– a sus jefes de área, donde se instruye manipular las
estadísticas de mortalidad de los salmones para ocultar las verdaderas cifras a
Sernapesca –la entidad fiscalizadora–, a fin de evitar multas y ver disminuir
las [...]

...and so on.

这篇关于如何从Google新闻RSS抓取Google新闻文章内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆