Amazing-Python-Scripts
67 строк · 2.0 Кб
1import requests
2from bs4 import BeautifulSoup
3
4
5class GoogleNews:
6"""
7Class - `GoogleNews`
8Example:
9```
10articles = GoogleNews(topic = "topic")
11```\n
12Methods :\n
131. ``.getArticles() | Response - Articles with title, descriptions, news source, date and link.
14"""
15
16def __init__(self, topic):
17self.topic = topic
18
19def getArticles(self):
20"""
21Class - `GoogleNews`
22Example:
23```
24articles = GoogleNews("github")
25articles.getArticles()
26```
27Returns:
28{
29"title": Tile of the article
30"description": Description of the article
31"news_source": News Source of the Article
32"date": Date the article was posted
33"link": Link to the article
34}
35"""
36url = "https://www.google.com/search?q=" + self.topic + "&tbm=nws"
37try:
38res = requests.get(url)
39soup = BeautifulSoup(res.text, "html.parser")
40
41articles_data = {"articles": []}
42
43articles = soup.find_all("a", jsname="ACyKwe")
44for a in articles:
45title = a.find("div", class_="BNeawe vvjwJb AP7Wnd").getText()
46date = a.find("span", class_="r0bn4c rQMQod").getText()
47desc = (
48a.find("div", class_="BNeawe s3v9rd AP7Wnd")
49.getText()
50.replace(date, "")
51)
52news_source = a.find(
53"div", class_="BNeawe UPmit AP7Wnd lRVwie"
54).getText()
55link = a["href"].replace("/url?q=", "")
56articles_data["articles"].append(
57{
58"title": title,
59"description": desc,
60"news_source": news_source,
61"date": date,
62"link": link,
63}
64)
65return articles_data
66except:
67return None
68