J.Salinas
J.Salinas

Reputation: 69

How to scrape Google News articles content from Google News 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.

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) 

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;

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

Upvotes: 3

Views: 5191

Answers (2)

Andrej Kesely
Andrej Kesely

Reputation: 195418

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()

Prints:

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.

Upvotes: 1

Raza
Raza

Reputation: 19

Clone this project,

git clone [email protected]:philipperemy/google-news-scraper.git gns
cd gns
sudo pip install -r requirements.txt
python main_no_vpn.py

Out put will be

{
    "content": "............",
    "datetime": "...",
    "keyword": "...",
    "link": "...",
    "title": "..."
},
{
    "content": "............",
    "datetime": "...",
    "keyword": "...",
    "link": "...",
    "title": "..."
}

Source : Here

Upvotes: 0

Related Questions