Genn9508 commited on
Commit
8dd1dfd
·
verified ·
1 Parent(s): 70ca3ec

Delete bd.py

Browse files
Files changed (1) hide show
  1. bd.py +0 -138
bd.py DELETED
@@ -1,138 +0,0 @@
1
- # Установка необходимых библиотек
2
- import sys
3
- !pip install feedparser requests beautifulsoup4
4
-
5
- import pandas as pd
6
- from datetime import datetime, timedelta
7
- from bs4 import BeautifulSoup
8
- import requests
9
- import re
10
-
11
- # 1. Определение RSS-ленты
12
- rss_url = 'https://vecherka.su/rss/'
13
- feed = feedparser.parse(rss_url)
14
-
15
- # 2. Определение диапазона дат (сегодня и вчера)
16
- today_date = datetime.now()
17
- yesterday_date = today_date - timedelta(days=1)
18
-
19
- # Форматирование дат в 'DD-MM-YYYY' для последовательного сравнения
20
- today_str = today_date.strftime('%d-%m-%Y')
21
- yesterday_str = yesterday_date.strftime('%d-%m-%Y')
22
-
23
- # 3. Инициализация списка для хранения новостей
24
- news_data = []
25
-
26
- # 4. Извлечение данных из RSS-ленты
27
- for entry in feed.entries:
28
- title = entry.title
29
- news_link = entry.link
30
-
31
- published_date_str = entry.published
32
-
33
- # Попытка парсинга даты в нескольких форматах
34
- parsed_date = None
35
- try:
36
- parsed_date = datetime.strptime(published_date_str, '%a, %d %b %Y %H:%M:%S %z')
37
- except ValueError:
38
- try:
39
- parsed_date = datetime.strptime(published_date_str, '%a, %d %b %Y %H:%M:%S %Z')
40
- except ValueError:
41
- try:
42
- parsed_date = datetime.strptime(published_date_str, '%a, %d %b %Y %H:%M:%S %z')
43
- except ValueError:
44
- try:
45
- date_parts = published_date_str.split(' ')[1:4]
46
- if len(date_parts) == 3:
47
- parsed_date = datetime.strptime(' '.join(date_parts), '%d %b %Y')
48
- else:
49
- raise ValueError("Insufficient date parts for parsing")
50
- except ValueError:
51
- print(f"Could not parse date for entry: {title} - {published_date_str}")
52
- continue
53
-
54
- if parsed_date:
55
- article_date_str = parsed_date.strftime('%d-%m-%Y')
56
-
57
- # Фильтрация статей, опубликованных сегодня или вчера
58
- if article_date_str == today_str or article_date_str == yesterday_str:
59
- image_urls = []
60
-
61
- # Извлечение изображений из media_content
62
- if 'media_content' in entry and len(image_urls) < 3:
63
- for media in entry.media_content:
64
- if media.get('type', '').startswith('image/') and media.get('url') and media.get('url') not in image_urls:
65
- image_urls.append(media['url'])
66
- if len(image_urls) == 3: break
67
-
68
- # Извлечение изображений из ссылок (rel='enclosure')
69
- if 'links' in entry and len(image_urls) < 3:
70
- for link in entry.links:
71
- if link.get('rel') == 'enclosure' and link.get('type', '').startswith('image/') and link.get('href') and link.get('href') not in image_urls:
72
- image_urls.append(link['href'])
73
- if len(image_urls) == 3: break
74
-
75
- # Извлечение изображений из HTML-содержимого (summary или content)
76
- html_content = ''
77
- if 'summary' in entry:
78
- html_content = entry.summary
79
- elif 'content' in entry and entry.content:
80
- html_content = entry.content[0].value
81
-
82
- if html_content and len(image_urls) < 3:
83
- soup = BeautifulSoup(html_content, 'html.parser')
84
- img_tags = soup.find_all('img')
85
- for img in img_tags:
86
- if img.get('src') and img.get('src') not in image_urls:
87
- image_urls.append(img['src'])
88
- if len(image_urls) == 3: break
89
-
90
- # Извлечение полного текста новости по ссылке
91
- full_text = ""
92
- try:
93
- response = requests.get(news_link)
94
- response.raise_for_status()
95
- article_soup = BeautifulSoup(response.text, 'html.parser')
96
- detail_text_div = article_soup.find('div', class_='detail-text')
97
- if detail_text_div:
98
- full_text = detail_text_div.get_text(separator=' ', strip=True)
99
- # Удаление предложений, содержащих 'подписывайтесь'
100
- full_text = re.sub(r'[^.!?]*\bподписывайтесь\b[^.!?]*[?.!]', '', full_text, flags=re.IGNORECASE)
101
- full_text = re.sub(r'\s+', ' ', full_text).strip()
102
-
103
- # Проверка на слово 'Реклама' и пропуск новости при обнаружении
104
- if re.search(r'\bРеклама\b', full_text, re.IGNORECASE):
105
- print(f"Skipping article '{title}' due to 'Реклама' in full text.")
106
- continue
107
- else:
108
- print(f"Could not find 'detail-text' div for article: {title}")
109
- except requests.exceptions.RequestException as e:
110
- print(f"Error fetching content for {news_link}: {e}")
111
- except Exception as e:
112
- print(f"Error parsing content for {news_link}: {e}")
113
-
114
- # Добавление извлеченных данных в список
115
- news_data.append({
116
- 'title': title,
117
- 'published': article_date_str,
118
- 'image_urls': image_urls,
119
- 'link': news_link,
120
- 'full_text': full_text
121
- })
122
-
123
- print(f"Extracted {len(news_data)} articles published today or yesterday.")
124
- if news_data:
125
- print("First extracted article example:", news_data[0])
126
- else:
127
- print("No articles found for today or yesterday.")
128
-
129
- # 5. Сохранение данных в CSV-файл
130
- df = pd.DataFrame(news_data)
131
- df['image_urls'] = df['image_urls'].apply(lambda x: ', '.join(x))
132
-
133
- csv_file_path = 'news_articles.csv'
134
- df.to_csv(csv_file_path, index=False, encoding='utf-8')
135
-
136
- print(f"Данные сохранены в файл: {csv_file_path}")
137
- print("Первые 5 строк сохраненного файла:")
138
- print(df.head())