Получение заголовков финансовых новостей за данный месяц - PullRequest
0 голосов
/ 08 мая 2019

У меня никогда не было возможности узнать о веб-скребке. Мне было интересно, что это я могу добавить в код ниже, чтобы получить заголовки за определенный период времени? Если бы можно было получать только финансовые новости, это было бы здорово!

import bs4
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen

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

soup_page=soup(xml_page,"xml")
news_list=soup_page.findAll("item")
# Print news title, url and publish date
for news in news_list:
    print(news.title.text)
    print(news.link.text)
    print(news.pubDate.text)
    print("-"*60)

Ответы [ 2 ]

0 голосов
/ 08 мая 2019

Попробуйте feedparser:

import feedparser
news_url=r'https://news.google.com/news/rss'
fp = feedparser.parse(news_url)

## number of entries
len(fp['entries'])

Выход:

38

Заголовок статьи с индексом '0':

print(fp['entries'][0]['title'])

Выход:

School Shooting in Colorado Leaves 1 Student Dead and 7 Injured - The New York Times

Вывести всю информацию для записи по индексу '0': Fp [ 'записи'] [0]

Выход:

{'title': 'School Shooting in Colorado Leaves 1 Student Dead and 7 Injured - The New York Times',
 'title_detail': {'type': 'text/plain',
  'language': None,
  'base': 'https://news.google.com/rss?hl=en-US&gl=US&ceid=US:en',
  'value': 'School Shooting in Colorado Leaves 1 Student Dead and 7 Injured - The New York Times'},
 'links': [{'rel': 'alternate',
   'type': 'text/html',
   'href': 'https://www.nytimes.com/2019/05/07/us/colorado-school-shooting.html'}],
 'link': 'https://www.nytimes.com/2019/05/07/us/colorado-school-shooting.html',
 'id': '52780288859641',
 'guidislink': False,
 'published': 'Wed, 08 May 2019 00:56:15 GMT',
 'published_parsed': time.struct_time(tm_year=2019, tm_mon=5, tm_mday=8, tm_hour=0, tm_min=56, tm_sec=15, tm_wday=2, tm_yday=128, tm_isdst=0),
 'summary': '<ol><li><a href="https://www.nytimes.com/2019/05/07/us/colorado-school-shooting.html" target="_blank">School Shooting in Colorado Leaves 1 Student Dead and 7 Injured</a>&nbsp;&nbsp;<font color="#6f6f6f">The New York Times</font></li><li><a href="https://www.foxnews.com/us/injuries-reported-unstable-situation-shots-fired-at-colorado-school-sheriff-says" target="_blank">Colorado school shooting leaves at least 1 dead, 7 injured, 2 in custody, sheriff\'s office says</a>&nbsp;&nbsp;<font color="#6f6f6f">Fox News</font></li><li><a href="https://www.cnn.com/2019/05/07/us/colorado-denver-area-school-shooting/index.html" target="_blank">Eight injured in school shooting in suburban Denver, 2 suspects are in custody</a>&nbsp;&nbsp;<font color="#6f6f6f">CNN</font></li><li><a href="https://kdvr.com/2019/05/07/president-trump-briefed-on-highlands-ranch-school-shooting/" target="_blank">President Trump briefed on Highlands Ranch school shooting</a>&nbsp;&nbsp;<font color="#6f6f6f">FOX 31 Denver</font></li><li><a href="https://www.oregonlive.com/nation/2019/05/sheriff-school-shooting-near-denver-injures-at-least-7.html" target="_blank">Sheriff: School shooting near Denver injures at least 7</a>&nbsp;&nbsp;<font color="#6f6f6f">OregonLive</font></li><li><strong><a href="https://news.google.com/stories/CAAqcQgKImtDQklTU2pvSmMzUnZjbmt0TXpZd1NqMEtFUWo1dV9ueWpZQU1FVWE5TGp2Z2NDNFJFaWhUYUc5MGN5Qm1hWEpsWkNCaGRDQnpZMmh2YjJ3Z2FXNGdTR2xuYUd4aGJtUnpJRkpoYm1Ob0tBQVAB?oc=5" target="_blank">View full coverage on Google News</a></strong></li></ol>',
 'summary_detail': {'type': 'text/html',
  'language': None,
  'base': 'https://news.google.com/rss?hl=en-US&gl=US&ceid=US:en',
  'value': '<ol><li><a href="https://www.nytimes.com/2019/05/07/us/colorado-school-shooting.html" target="_blank">School Shooting in Colorado Leaves 1 Student Dead and 7 Injured</a>&nbsp;&nbsp;<font color="#6f6f6f">The New York Times</font></li><li><a href="https://www.foxnews.com/us/injuries-reported-unstable-situation-shots-fired-at-colorado-school-sheriff-says" target="_blank">Colorado school shooting leaves at least 1 dead, 7 injured, 2 in custody, sheriff\'s office says</a>&nbsp;&nbsp;<font color="#6f6f6f">Fox News</font></li><li><a href="https://www.cnn.com/2019/05/07/us/colorado-denver-area-school-shooting/index.html" target="_blank">Eight injured in school shooting in suburban Denver, 2 suspects are in custody</a>&nbsp;&nbsp;<font color="#6f6f6f">CNN</font></li><li><a href="https://kdvr.com/2019/05/07/president-trump-briefed-on-highlands-ranch-school-shooting/" target="_blank">President Trump briefed on Highlands Ranch school shooting</a>&nbsp;&nbsp;<font color="#6f6f6f">FOX 31 Denver</font></li><li><a href="https://www.oregonlive.com/nation/2019/05/sheriff-school-shooting-near-denver-injures-at-least-7.html" target="_blank">Sheriff: School shooting near Denver injures at least 7</a>&nbsp;&nbsp;<font color="#6f6f6f">OregonLive</font></li><li><strong><a href="https://news.google.com/stories/CAAqcQgKImtDQklTU2pvSmMzUnZjbmt0TXpZd1NqMEtFUWo1dV9ueWpZQU1FVWE5TGp2Z2NDNFJFaWhUYUc5MGN5Qm1hWEpsWkNCaGRDQnpZMmh2YjJ3Z2FXNGdTR2xuYUd4aGJtUnpJRkpoYm1Ob0tBQVAB?oc=5" target="_blank">View full coverage on Google News</a></strong></li></ol>'},
 'source': {'href': 'https://www.nytimes.com', 'title': 'The New York Times'}}
0 голосов
/ 08 мая 2019

Вот моя попытка решения.Проверьте метод get_headlines (start_date, end_date), который я включил в конце.

Я конвертирую формат в XML-файле, который вы добавили, в объект datetime и сравниваю его с другими объектами datetime, которые я указал, чтобы получить логическое значениезначение.Мы можем определить, попадает ли статья в наш диапазон, основываясь на отображаемых логических значениях, а затем выбрать только эти статьи.

import bs4
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen
from datetime import datetime

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

soup_page=soup(xml_page,"xml")
news_list=soup_page.findAll("item")
# Print news title, url and publish date
for news in news_list:
    print(news.title.text)
    print(news.link.text)
    print(news.pubDate.text)
    print("-"*60)
    print("Date Object: ", datetime.strptime(news.pubDate.text, "%a, %d %B %Y %X %Z"))

    sample_end_date = "Wed, 08 May 2019 18:17:04 GMT"
    print(datetime.strptime(sample_end_date, "%a, %d %B %Y %X %Z") > datetime.strptime(news.pubDate.text, "%a, %d %B %Y %X %Z"))
    #datetime of article is less than the datetime of the end date

    sample_start_date = "Wed, 08 May 2019 00:00:00 GMT"
    print(datetime.strptime(sample_start_date, "%a, %d %B %Y %X %Z") < datetime.strptime(news.pubDate.text, "%a, %d %B %Y %X %Z"))
    #datetime of article is greater than the datetime of the start date


   #If both values are true, then we know that the article falls within the range we specified. If not, then it falls outside the range.'''
def get_headlines(start_date= input("Enter start date. \nFollow this format exactly for date input Wed, 08 May 2019 18:17:04 GMT: \n"), end_date= input("Enter end date. \n")):
    start_date_object = datetime.strptime(start_date, "%a, %d %B %Y %X %Z")
    end_date_object = datetime.strptime(end_date, "%a, %d %B %Y %X %Z")
    news_url="https://news.google.com/news/rss"

    Client=urlopen(news_url)
    xml_page=Client.read()
    Client.close()

    soup_page=soup(xml_page,"xml")
    news_list=soup_page.findAll("item")
    # Print news title, url and publish date
    print(f"All articles from {start_date_object} to {end_date_object}: \n")
    for news in news_list:
        if (end_date_object>datetime.strptime(news.pubDate.text, "%a, %d %B %Y %X %Z")>start_date_object):
            print(news.title.text)
            print(news.link.text)
            print(news.pubDate.text)
            print("-"*60)



get_headlines()

Вот пример выходных данных с полуночи среды GMT до 18:00 среды GMT:

Введите дату начала.

Следуйте этому формату точно для ввода даты Ср, 08 мая 2019 18:17:04 GMT:

Ср, 08 мая 2019 00:00:00 GMT

Введите конецДата.

Ср, 08 мая 2019 г. 18:17:04 GMT

Все статьи с 2019-05-08 00:00:00 до 2019-05-08 18:17:04:

Трамп проинформирован о стрельбе в Колорадо, говорит Белый дом - Fox News https://www.foxnews.com/us/trump-briefed-on-colorado-shooting-white-house-says-politicians-offer-condolences

Ср, 08 мая 2019 08:08:22 GMT

Иранский лидер объявляет о частичном выходе из ядерной сделки- CNN https://www.cnn.com/2019/05/08/middleeast/iran-nuclear-deal-intl/index.html

Ср, 08 мая 2019 г. 09:40:00 по Гринвичу

Китай отслеживает практически все аспекты торговой сделки США: источники - CNBC https://www.cnbc.com/2019/05/08/china-backtracked-on-nearly-all-aspects-of-us-trade-deal-sources.html

Ср, 08 мая 2019 03:12:00 GMT

Главный помощник Барра видел, как Россия зондирует, как немногие в мире Трампа - POLITICO https://www.politico.com/story/2019/05/08/brian-rabbitt-william-barr-1309751

Ср, 08 мая 2019 09:03: 00 GMT

WH поручает бывшему адвокату не выполнять повестку в Конгресс - Новости ABC https://abcnews.go.com/Politics/white-house-instruct-counsel-comply-congressional-subpoena/story?id=62873987

Ср, 08 мая 2019 00:10:00 GMT

Трамп держитМитинг во Флориде Panhandle, с фондами помощи в случае стихийных бедствий - NPR https://www.npr.org/2019/05/08/720803270/as-hurricane-relief-stalls-in-d-c-trump-to-rally-base-in-florida-panhandle

Ср, 08 мая 2019 09:01:00 GMT

Колорадский школьник STEM Брендан Биали помог разоружитьсяunman - NBC News https://www.nbcnews.com/news/us-news/colorado-stem-school-student-brendan-bialy-helped-disarm-gunman-n1003181

Ср, 08 мая 2019 09:52:00 GMT

Помпео с неожиданным визитом в Ирак на фоне растущей напряженности в Иране - Aljazeera.com https://www.aljazeera.com/news/2019/05/pompeo-surprise-iraq-visit-rising-iran-tensions-190508034718722.html

Ср, 08 мая 2019 г. 04:18:00 GMT

На выборах в Южной Африке Рамапозе грозит приговор разочарованным избирателям - The New York Times https://www.nytimes.com/2019/05/08/world/africa/south-africa-election.html

Ср, 08 мая 2019 г. 07: 39: 49 GMT

Взрыв в Лахоре: по меньшей мере шесть человек погибли в результате взрыва возле храма Суфи - CNN https://www.cnn.com/2019/05/08/asia/lahore-blast-intl/index.html

Ср, 08 мая 2019 г. 06:15:00 GMT

Водители Uber собираются протестовать по всему миру в преддверии IPO компании на 90 миллиардов долларов - CNBC https://www.cnbc.com/2019/05/08/uber-drivers-strike-over-low-wages-benefits-ahead-of-ipo.html

Ср, 08 мая 2019 08:51:13 GMT

Миллиардер Чарли Мангер сравнивает инвесторов Биткойн«Иуде Искариоту» - Ethereum World News https://ethereumworldnews.com/billionaire-charlie-munger-compares-bitcoin-investors-to-judas-iscariot/

Ср, 08 мая 2019 00:21:12 GMT

Android TV выиграет, когда Ассистент будет связан с данными телепрограмм в прямом эфире - Engadgethttps://www.engadget.com/2019/05/08/google-assistant-epg-android-tv-play-store/

Ср, 08 мая 2019 г. 08:35:40 GMT

Реформа тюрьмы Ким Кардашьян: Запад Ким Кардашьянпомог освободить 17 человек из тюрьмы за последние 90 дней - Новости CBS https://www.cbsnews.com/news/kim-kardashian-west-has-helped-free-17-people-from-prison-in-the-last-90-days/

Ср, 08 мая 2019 05:07:00 GMT

Vampire Weekend выступают с Хаимом на «Фэллоне»: Часы - Вилы https://pitchfork.com/news/vampire-weekend-perform-with-haim-on-fallon-watch/

Ср, 08 мая 2019 г. 04:40:00 GMT

Джордж Клуни рассказывает, как королевский ребенок Гарри и Меган делится своим днем ​​рождения - Daily Mail https://www.dailymail.co.uk/tvshowbiz/article-7004777/George-Clooney-reveals-Prince-Harry-Meghan-Markles-newborn-shares-birthday.html

Ср, 08 мая 2019 г. 06:59:43 GMT

Кувшин из «Окленда А» Майк Файерс выбрасывает 2-ую карьеру без нападающих, бьет красных - Fox News https://www.foxnews.com/sports/athletics-fiers-pitching-no-hitter-beats-reds

Ср, 08 мая2019 06:36:18 GMT

Джо Намат не выпивал с момента своего неловкого момента в прямом эфире - NBC Sports http://profootballtalk.nbcsports.com/2019/05/07/joe-namath-hasnt-had-a-drink-since-his-embarrassing-moment-on-live-tv/

Ср, 08 мая 2019 01:28:00GMT

Моряки упали до .500 с очередным обвалом КПЗ, что привело к потере 5-4 в Бронксе - Seattle Times https://www.seattletimes.com/sports/mariners/mariners-fall-to-500-with-another-bullpen-collapse-that-leads-to-5-4-loss-in-bronx/

Ср, 08 мая 2019 г. 03:20:00 GMT

Подвинься, кремниевые переключатели: есть новый способ вычислений - Phys.org https://phys.org/news/2019-05-silicon.html

Ср, 08 мая 2019 07:19:31 GMT

Астероид НАСА:Космическое агентство проливает свет на смелый план защиты астероидов - «Идеальная цель» - Express.co.uk https://www.express.co.uk/news/science/1123704/NASA-asteroid-double-redirection-test-NASA-DART-asteroid-Didymos

Ср, 08 мая 2019 г. 07:43:00 GMT

RFK Jr. IsНаш брат и дядя.Он трагически ошибается в отношении вакцин.- ПОЛИТИКО https://www.politico.com/magazine/story/2019/05/08/robert-kennedy-jr-measles-vaccines-226798

Ср, 08 мая 2019 г. 09:05:00 по Гринвичу

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...